본문 바로가기
언어/JAVA

Comparable, Comparator 인터페이스

by step 1 2021. 5. 2.
반응형

정렬을 위해 Comparable, Comparator 인터페이스 구현

TreeSet 클래스 활용

  • 객체의 정렬에 사용하는 클래스
  • Set 인터페이스를 구현하여 중복을 허용하지 않고, 오름차순이나 내림차순으로 객체를 정렬할 수 있음
  • 내부적으로 이진검색트리(binary search tree)로 구현됨
  • 이진검색트리에 저장하기 위해 각 객체를 비교해야 함
  • 비교 대상이 되는 객체에 Comparable이나 Comparator 인터페이스를 구현 해야 TreeSet에 추가 될 수 있음
  • String, Integer등 JDK의 많은 클래스들이 이미 Comparable을 구현했다

Comparable 이용

package ch49;

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 = (Member) obj; // Member 클래스로 다운 캐스팅
			if (this.memberId == member.memberId) { // 기존 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;
//		}
		
		return (this.memberId - member.memberId);
	}

}
package ch49;

import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;

public class MemberTreeSet {

	private TreeSet<Member> treeSet;
	
	public MemberTreeSet() {
		treeSet = new TreeSet<>();
	}
	
	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();
			
			if (member.getMemberId() == 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();
	}
}
package ch49;

import java.util.TreeSet;

public class MemberTreeSetTest {

	public static void main(String[] args) {
		
		TreeSet<String> set = new TreeSet<>();
		set.add("홍길동");
		set.add("강감찬");
		set.add("이순신");
		
		System.out.println(set);    // 정렬되어 나옴
		
		MemberTreeSet memberTreeSet = new MemberTreeSet();
		
		Member memberHong = new Member(1004, "홍길동");
		Member memberLee = new Member(1001, "이순신");
		Member memberKim = new Member(1002, "김유신");
		Member memberKang = new Member(1003, "강감찬");
		
		memberTreeSet.addMember(memberHong);
		memberTreeSet.addMember(memberLee);
		memberTreeSet.addMember(memberKim);
		memberTreeSet.addMember(memberKang);

		memberTreeSet.showAllMember();
		
		memberTreeSet.removeMember(memberKang.getMemberId());
		memberTreeSet.showAllMember();
//		
	}
}

 

Comparator의 활용: 이미 Comparable이 구현된 경우 Comparator로 비교하는 방식을 다시 구현할 수 있음

 

package ch49;

import java.util.Comparator;
import java.util.TreeSet;

public class Member implements Comparator<Member> {

	private int memberId; // 회원 아이디
	private String memberName; // 회원 이름

	public Member(int memberId, String memberName) { // 생성자
		this.memberId = memberId;
		this.memberName = memberName;
	}
    
	public Member() {
		
	}

	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 = (Member) obj; // Member 클래스로 다운 캐스팅
			if (this.memberId == member.memberId) { // 기존 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;
////		}
//		
//		return (this.memberId - member.memberId);
//	}

	@Override
	public int compare(Member member1, Member member2) {
		// TODO Auto-generated method stub
		return (member1.memberId - member2.memberId);
	}

}
package ch49;

import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;

public class MemberTreeSet {

	private TreeSet<Member> treeSet;
	
	public MemberTreeSet() {
		treeSet = new TreeSet<Member>(new 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();
			
			if (member.getMemberId() == 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();
	}
}
package ch49;

import java.util.Comparator;
import java.util.TreeSet;

class MyCompare implements Comparator<String> {

	@Override
	public int compare(String s1, String s2) {
		
		return s1.compareTo(s2) * -1;
	}
	
}
public class MemberTreeSetTest {

	public static void main(String[] args) {
		/*
		TreeSet<String> set = new TreeSet<>();
		set.add("홍길동");
		set.add("강감찬");
		set.add("이순신");
		
		System.out.println(set);    // 정렬되어 나옴
		
		MemberTreeSet memberTreeSet = new MemberTreeSet();
		
		Member memberHong = new Member(1004, "홍길동");
		Member memberLee = new Member(1001, "이순신");
		Member memberKim = new Member(1002, "김유신");
		Member memberKang = new Member(1003, "강감찬");
		
		memberTreeSet.addMember(memberHong);
		memberTreeSet.addMember(memberLee);
		memberTreeSet.addMember(memberKim);
		memberTreeSet.addMember(memberKang);

		memberTreeSet.showAllMember();
		
		memberTreeSet.removeMember(memberKang.getMemberId());
		memberTreeSet.showAllMember();
	*/
		TreeSet<String> set = new TreeSet<>(new MyCompare());
		set.add("Park");
		set.add("Kim");
		set.add("Lee");
		System.out.println(set);
	}
}

 

반응형

'언어 > JAVA' 카테고리의 다른 글

여러 내부 클래스  (0) 2021.05.08
Map 인터페이스  (0) 2021.05.02
Set 인터페이스  (0) 2021.05.02
Iterator  (0) 2021.05.02
List 인터페이스  (0) 2021.05.02