黑马程序员技术交流社区
标题:
遇到一个关于集合的问题,请各位帮我看看,谢谢大家
[打印本页]
作者:
黑色雨季
时间:
2015-8-20 08:04
标题:
遇到一个关于集合的问题,请各位帮我看看,谢谢大家
public class ArrayListDemo3 {
public static void main(String[] args) {
// 创建集合对象
ArrayList array = new ArrayList();
// 创建学生对象
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("林志玲", 40);
Student s3 = new Student("凤姐", 35);
Student s4 = new Student("芙蓉姐姐", 18);
Student s5 = new Student("翠花", 16);
Student s6 = new Student("林青霞", 27);
Student s7 = new Student("林青霞", 18);
// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
array.add(s5);
array.add(s6);
array.add(s7);
// 创建新集合
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 x = 0; x < newArray.size(); x++) {
Student s = (Student) newArray.get(x);
System.out.println(s.getName() + "---" + s.getAge());
}
}
package cn.itcast_04;
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
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 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;
}
}
冲写的equals 方法看不懂,能帮我看看吗
作者:
黑色雨季
时间:
2015-8-20 08:09
还有没有其他重写的方法呢,这个真心看不懂
作者:
liuch111
时间:
2015-8-20 08:40
为了效率和安全性,官方版的equals 写的有点复杂,前面加了很多判断语句,满足判断语句则直接返回结果
public boolean equals(Object obj) {
if (this == obj) //判断两个对象的地址是否相等,相等则表示真,后面不执行
return true;
if (obj == null) // 对象为null 放回假,表示不相等
return false;
if (getClass() != obj.getClass()) //通过反射去比较两个对象的类 是否相同
return false;
Student other = (Student) obj; //强制转换
if (age != other.age) //比较年龄....
return false;
if (name == null) { //比较 name
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true; //前面语句执行都没有返回结果, 则最后直接返回真
}
复制代码
作者:
liuch111
时间:
2015-8-20 08:42
本帖最后由 liuch111 于 2015-8-20 10:08 编辑
觉得复杂 你可以自己手动改!!
比如:
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
return false;
Student p =(Student)obj:
return this.name.equals(p.name)&&this.age==p.age;
}
复制代码
作者:
黑色雨季
时间:
2015-8-20 09:31
liuch111 发表于 2015-8-20 08:42
觉得复杂 你可以自己手动改!!
比如:
谢谢,,,,,
作者:
放学后来我家
时间:
2015-8-20 10:02
还没看到集合
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2