한 번에 끝내는 Java/Spring 웹 개발 마스터
- Comparabe
- Comparator
public class Member implements Comparable<Member> {
private int memberId; // 회원 아이디
private String memberName; // 회원 이름
public Member(int memberId, String memberName) { // 생성자
this.memberId = memberId;
this.memberName = memberName;
}
public int getMemberId() { //
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
@Override
public int hashCode() {
return memberId;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Member) {
Member member = (Member) obj;
if (this.memberId == member.memberId)
return true;
else
return false;
}
return false;
}
@Override
public String toString() { // toString 메소드 오버로딩
return memberName + " 회원님의 아이디는 " + memberId + "입니다";
}
@Override
public int compareTo(Member member) {
if(this.memberId > member.memberId)
return 1;
else if(this.memberId < member.memberId)
return -1;
else
return 0;
}
}
import java.util.TreeSet;
import java.util.Iterator;
public class MemberTreeSet {
private TreeSet<Member> treeset;
public MemberTreeSet() {
treeset = new TreeSet<Member>();
}
public void addMember(Member member) {
treeset.add(member);
}
public boolean removeMember(int memberId) {
Iterator<Member> ir = treeset.iterator();
while (ir.hasNext()) {
Member member = ir.next();
int tempId = member.getMemberId();
if (tempId == memberId) {
treeset.remove(member);
return true;
}
}
System.out.println(memberId + "가 존재하지 않습니다");
return false;
}
public void showAllMember() {
for (Member member : treeset) {
System.out.println(member);
}
System.out.println();
}
}
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class MyCompare implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
return (s1.compareTo(s2)) *-1 ;
}
}
public class ComparatorTest {
public static void main(String[] args) {
Set<String> set = new TreeSet<String>(new MyCompare());
set.add("aaa");
set.add("ccc");
set.add("bbb");
System.out.println(set);
}
}
TreeSet & Comparator