我创建了一个对象Student,使用Comparable与getter/setters以及一个覆盖compareTo的方法。在单独的文件中,对象的数组列表由文本文件填充。现在我需要将arraylist中的值与另一个Student对象进行比较。使用Comparable的compareTo来比较一个对象与arraylist中的元素
文件被用来创建一个ArrayList如下:
try {
private static ArrayList<Student> array = new ArrayList<Student>();
File file = new File("students.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String inline = scanner.nextLine();
String[] split = inline.split(":");
Student myStudent = new Student();
myStudent.setUsername(split[0]);
myStudent.setPassword(split[1]);
array.add(myStudent);
}
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println("ERROR.");
}
文本文件看起来像这样:
约翰:密码1
简:密码2
杰克:password3
(每行一个,中间没有空行。)
而在一个单独的方法所创建的学生对象相比,在数组列表中的元素:
Student aStudent = new Student();
aStudent.setUsername("student");
aStudent.setPassword("password");
boolean found = false;
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break;
}
else
{
System.out.println("No such records found!");
found = false;
break;
}
System.out.println(found);
}
的问题是,该物体aStudent不被用在数组列表中的对象进行比较。它不会为compareTo调用打印任何东西(一个-1,0或1),但它总是显示找到的是真的,即使它在文件中没有与aStudent匹配的情况下应该是false(那里与用户名“student”或密码“password”不匹配)。
所有在一起我的代码符合和工作 - 它只是工作不正确。
对不起,如果这听起来很混乱。简而言之,我的问题是,如何使用Comparable接口和compareTo将arraylist的对象与另一个对象进行比较?如果你能告诉我我做错了什么,那么加号就是了。
预先感谢您。
编辑
这里是compareTo方法的重载:
public int compareTo(Student obj){
int result = 1;
if ((this.Username.compareToIgnoreCase(object.Username) < 0) || (this.Password.compareTo(object.Password) < 0))
{
result = -1;
}
else if ((this.Username.compareToIgnoreCase(object.Username) == 0) && (this.Password.compareTo(object.Password) == 0))
{
result = 0;
}
return result;
}
你在实现Comparable接口并重写compareTo方法吗?这里是有用的链接:http://stackoverflow.com/questions/18757805/implementing-custom-compareto – 2014-10-08 03:22:31
@sushanttambare感谢您的回复和链接。是的,我重写compareTo方法的方式类似于链接中显示的方式。当我创建和比较两个Student对象(例如,aStudent.compareTo(bStudent))时,它按预期工作,所以我猜想问题在于arraylist,但我无法弄清楚导致问题的原因。 – 2014-10-08 03:26:34
你似乎过早地打破了循环。也就是说,'else'语句打破了循环,这意味着你只会比较数组中的第一个元素,而没有更多... – MadProgrammer 2014-10-08 03:28:44