[code="java"]
public static void main(String[] args) throws Exception {
List students = new ArrayList();
students.add(new Student("WTCCNDEPT1", 0, 0, 2, 1));
students.add(new Student("WTCCNDEPT1", 0, 0, 3, 1));
students.add(new Student("WTCCNDEPT1", 0, 0, 2, 1));
students.add(new Student("WTCCNDEPT2", 0, 0, 3, 2));
students.add(new Student("WTCCNDEPT2", 0, 0, 3, 2));
Set studsSet = new HashSet(students);
List newStuds = new ArrayList();
for (Student student : studsSet) {
String company = student.getCompany();
boolean found = false;
for (Student stud : newStuds) {
if (company.equals(stud.getCompany())) {
stud.setNo1(stud.getNo1() + student.getNo1());
stud.setNo2(stud.getNo2() + student.getNo2());
stud.setNo3(stud.getNo3() + student.getNo3());
stud.setNo4(stud.getNo4() + student.getNo4());
found = true;
break;
}
}
if (!found) {
newStuds.add(student);
}
}
for (Student student : newStuds) {
System.out.println(student);
}
}
[/code]
[code="java"]
public class Student{
private String company;
private int no1;
private int no2;
private int no3;
private int no4;
public Student(String company, int no1, int no2, int no3, int no4) {
this.company = company;
this.no1 = no1;
this.no2 = no2;
this.no3 = no3;
this.no4 = no4;
}
// 省略 getter和setter
@Override
public int hashCode() {
int hash = company.hashCode();
hash = hash * 37 + no1;
hash = hash * 37 + no2;
hash = hash * 37 + no3;
hash = hash * 37 + no4;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Student) {
Student other = (Student) obj;
return company.equals(other.getCompany()) && no1 == other.getNo1() && no2 == other.getNo2()
&& no3 == other.getNo3() && no4 == other.getNo4();
}
return false;
}
@Override
public String toString() {
return String.format("%s\t%d\t%d\t%d\t%d", company, no1, no2, no3, no4);
}
}
[/code]