(자바) Comparble 정리(equals, compareTo)

만약 Node라는 클래스를 만들고 이를 PriorityQueue에 보관할 때,
크기를 비교하기 위해서는 Comparable를 구현해야 한다.

이때,  크기 비교는 compareTo를 오버라이딩 해야한다.


예)

PriorityQueue<Node> pq=new PriorityQueue<Node>();
//우선순위 큐에 중복되는 number가 있는지 확인
Node temp=new Node(10);
if(pq.contains(temp))//-------------------------------->equals메소드에 의해 중복이 있으면 true를 반환한다.

Class Node{
  int count;
  int number;

  public Node(long number){
this.number=number;
this.count=0;
}


@Override
public int compareTo(C o) {
long otherNumber=o.number;
int otherCount=o.count;
// TODO Auto-generated method stub
if(this.count>otherCount){
return -1;
}
else if(this.count==otherCount){
if(this.number<otherNumber)
return -1;
else
return 1;
}
else
  return 1;
}
}


댓글

이 블로그의 인기 게시물

(네트워크)폴링방식 vs 롱 폴링방식

(ElasticSearch) 결과에서 순서 정렬

(18장) WebSocekt과 STOMP를 사용하여 메시징하기