去除ArrayList集合中的重复自定义对象元素

在这里插入图片描述
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java后端指南

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值