import java.util.Comparator;
public class Member implements Comparable<Member>{
private int id;
private String name;
public Member() {}
public Member(int id, String name) {
this.id = id;
this.name = name;
}
public int getID() {
return this.id;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.id + " : " + this.name;
}
@Override
public int hashCode() {
return this.id;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Member) {
Member m = (Member)obj;
if(this.getID() == m.getID()) {
return true;
}
}
return false;
}
@Override
public int compareTo(Member m) {
return this.name.compareTo(m.getName());
}
}
================================================
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Member> ts = new TreeSet<Member>();
ts.add(new Member(1007, "LimEunHa"));
ts.add(new Member(1012, "JangBoYoung"));
ts.add(new Member(1002, "AhnJinWoo"));
ts.add(new Member(1001, "KimSiYeon"));
ts.add(new Member(1007, "EunHa"));
ts.add(new Member(1002, "JinWoo"));
for(Member m : ts) {
System.out.println(m);
}
}
}
=============================================
Result<br/>
1002:AhgnJinWoo<br/>
1007:EunHa<br/>
1012:JangBoYoung<br/>
1002:JinWoo<br/>
1001:KimSiYeoun<br/>
1007:LimEunHa<br/>
此代码执行排序,但允许复制。我不允许重复。我要按字符串(名称)排序,按int(id)检查重复。
1条答案
按热度按时间jmo0nnb31#
你可以用
ArrayList
存储成员对象的步骤从成员列表流中获取不同的成员并进行排序
输出: