日期:2014-05-20  浏览次数:20776 次

ArrayList如何判断一个符合条件的类的实例是否存在?
List<Student> l = new ArrayList<Student>();
Student是一个类,类里面包含两个变量,现在Student s = new Student("某人","某号");
如何判断在ArrayList的数组中存在一个除了地址其他和s一模一样的Student类(也就是里面的变量的值是某人和某号)??????

------解决方案--------------------
Student类重写equals方法。
或者用Student两个变量分别比较,两个对象的两个变量分别对应相等,则两个对象相等。
------解决方案--------------------
同意brightyq的回复,但是如果要提高搜索的速度,建议使用HashMap作为容器
------解决方案--------------------
Student类重写equals方法。
 

 while循环遍历对象用.equals(new Student("某人","某号"));比较

 如果为ture 就存在
 
------解决方案--------------------
探讨

典型的拿来主义。
建议楼下不要回答。
同时建议楼主自己找答案。

------解决方案--------------------
----------------------------Student Class--------------
public class Student {
private String name;

private int number;

public Student(String name, int number) {
this.name = name;
this.number = number;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getNumber() {
return number;
}

public void setNumber(int number) {
this.number = number;
}

@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
Student s = (Student) o;
if (o instanceof Student && this.getName().equals(s.getName())
&& this.getNumber() == s.getNumber())
return true;

return false;
}

@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.getNumber() * 3;
}
}


----------------------------Main Class--------------

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

public class TestStudent {
public static void main(String[] args) {

Student one = new Student("same", 20);

Student lily = new Student("lily", 20);

Student jack = new Student("jack", 20);

Student two = new Student("same", 20);

Student three = new Student("same", 20);

Student four = new Student("same", 20);

List<Student> l = new ArrayList<Student>();

l.add(one);
l.add(two);
l.add(three);
l.add(four);
l.add(lily);
l.add(jack);

Iterator it = l.iterator();
it.next();
for (Student stu : l) {

while (it.hasNext()) {

Student s = (Student) it.next();

if (stu.equals(s)) {
System.out.println("The same student's name are : " + stu.getName());
}

}
}

}
}