我有一个包含许多对象的数组列表。我想从它删除重复的对象..我尝试使用TreeSet和Comparator下面的选项,但它不起作用。以下类对象添加在列表
中 public class Student {
private String name;
private String location;
private int score;
private int age;
private String department;
Student(){}
Student(String sName,String loc,int ag,int scr,String dep){
setName(sName);
setLocation(loc);
setScore(scr);
setAge(ag);
setDepartment(dep);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
以下是我的主要课程
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class MyMain {
public static void main(String[] args) {
Student s1= new Student("John","Aus",25,100,"Finance");
Student s2= new Student("John","Aus",25,100,"Finance");
Student s3= new Student("John","Aus",26,100,"Finance");
Student s4= new Student("Alex","Ind",20,101,"Finance");
Student s5= new Student("Alex","Ind",20,101,"Finance");
Student s6= new Student("Alex","Ind",28,101,"Finance");
ArrayList<Student> studentsList= new ArrayList<Student>();
studentsList.add(s1);
studentsList.add(s2);
studentsList.add(s3);
studentsList.add(s4);
studentsList.add(s5);
studentsList.add(s6);
for(int i=0;i<studentsList.size();i++){
Student s=(Student)studentsList.get(i);
System.out.println(i+ " "+s.getName()+" "+s.getLocation()+" "+s.getAge()+" "+s.getScore()+" "+s.getDepartment());
}
Set set = new TreeSet(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if( s1.getName().equalsIgnoreCase(s2.getName()) && s1.getLocation().equalsIgnoreCase(s2.getLocation()) && s1.getScore()==s2.getScore()){
return 0;
}
return 1;
}
});
set.addAll(studentsList);
studentsList.clear();
studentsList.addAll(set);
System.out.println("---------Final Result----------");
for(int i=0;i<studentsList.size();i++){
Student s=(Student)studentsList.get(i);
System.out.println(i+ " "+s.getName()+" "+s.getLocation()+" "+s.getAge()+" "+s.getScore()+" "+s.getDepartment());
}
}
}
我想从列表中删除包含相同&#39;名称&#39;,&#39;位置&#39;和&#39;得分&#39;
我在运行程序时得到以下输出
0 John Aus 100 25 Finance
1 John Aus 100 26 Finance
2 Alex Ind 101 20 Finance
3 Alex Ind 101 28 Finance
但是我的预期输出是
0 John Aus 100 25 Finance
1 Alex Ind 101 20 Finance
请帮我解决这个问题。这种方法是否正确?另外,我想保持Student类的完整性(不能覆盖equals和hashCode)
请咨询
答案 0 :(得分:0)
这就是为什么你会得到重复的原因 - 因为分数不同.. 你刚刚超过年龄和得分参数
Student(String sName,String loc,int scr,int ag,String dep)
Student s1= new Student("John","Aus",25,100,"Finance");