<span>Set集合相关的面试题</span>

1、在List内去除重复数字值,要求尽可能简单

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class TestC{
    public static void main(String[] args) {
       ArrayList<Integer> arrayList = new ArrayList<>();
       arrayList.add(1);
       arrayList.add(2);
       arrayList.add(3);
       arrayList.add(2);
       arrayList.add(5);
       arrayList.add(1);

       List list = updateList(arrayList);

       Iterator iterator = list.iterator();
       while(iterator.hasNext()){
    	   System.out.println(iterator.next());
       }
    }

        //去除重复数字值的方法
	public static List updateList(List list){
	      HashSet set = new HashSet();
	      set.addAll(list);
	      return new ArrayList(set);
	}
	
}

运行结果;
1 2 3 5

2、HashSet存储过程

Person类:

package setdemo;

public class Person {
	int id;
	String name;
	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + "]";
	}
	//set、get省略
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

主类:

package setdemo;

import java.util.HashSet;

//集合Set面试题
public class Test_set {
	public static void main(String[] args) {
		HashSet set = new HashSet();
		Person person1 = new Person(101,"A");
		Person person2 = new Person(102,"B");
		
		set.add(person1);
		set.add(person2);
		System.out.println(set);
		
		person1.name = "C";
		set.remove(person1);
		System.out.println(set);
		
		set.add(new Person(101,"C"));
		System.out.println(set);
		
		set.add(new Person(101,"A"));
		System.out.println(set);
		
	}
}

运行结果:

[Person [id=101, name=A], Person [id=102, name=B]]
[Person [id=101, name=C], Person [id=102, name=B]]
[Person [id=101, name=C], Person [id=102, name=B], Person [id=101, name=C]]
[Person [id=101, name=C], Person [id=102, name=B], Person [id=101, name=A], Person [id=101, name=C]]
全部评论

相关推荐

勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
kyw_:接好运
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务