去除集合中自定义重复字符串元素案例(contains()方法的底层依赖equals()方法)...

第一部分:

//创建学生类
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student(){
super();
}

public Student(String name, int age){
this.name = name;
this.age = 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;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;

Student student = (Student) o;

if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;

}

@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

第二部分:
public class Array {
public static void main(String[] args){
//创建集合对象
ArrayList list = new ArrayList();
//创建学生对象
Student s1 = new Student("苏有朋",38);
Student s2 = new Student("林志颖",40);
Student s3 = new Student("蔡依林",35);
Student s4 = new Student("林志颖",40);
Student s5 = new Student("苏有朋",38);
Student s6 = new Student("张无忌",28);
Student s7 = new Student("周芷若",18);
//添加到集合
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
//创建新的集合
ArrayList list1 = new ArrayList();
//遍历旧的集合
Iterator it = list.iterator();
while (it.hasNext()){
Student s = (Student) it.next();
if (!list1.contains(s)){
list1.add(s);
}
}
//遍历新的集合
for (int x=0;x<list1.size();x++){
Student s = (Student)list1.get(x);
System.out.println(s.getName()+"-----"+s.getAge());
}
}
}

转载于:https://www.cnblogs.com/WTBK/p/9405713.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值