在这里插入图片描述
student类:

public class student {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public student() {
		super();
		
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	//需要重写equal方法
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		student other = (student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
	

}

test类:

ArrayList array=new ArrayList();
	
		student s1=new student("kk",23);
		student s2=new student("xx",34);
		student s3=new student("yy",45);
		student s4=new student("yy",45);
		student s5=new student("yy",45);
		
		array.add(s3);
		array.add(s2);
		array.add(s1);
		
		ArrayList newArray=new ArrayList();
		Iterator it=array.iterator();
		while(it.hasNext()){
			student s=(student)it.next();
			if(!newArray.contains(s)){
				newArray.add(s);
			}
		}
		for(int i=0;i<newArray.size();i++){
			student ss=(student)newArray.get(i);
			System.out.println(ss.getName()+"----"+ss.getAge());
		}

结果:

yy----45
xx----34
kk----23

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐