2012-09-02 2 views
3

im은 콜렉션을 사용하여 작업합니다.이 점을 이해할 수 없습니다 ... Node 클래스의 "data"변수를 기반으로 compareTo() 메소드를 오버라이드하고 싶습니다. collection.sort() ArrayList의를 정렬하는 ..compareTo()를 generics 및 collection으로 구현하는 경우

public class Node<E> implements Comparable<E>{ 

    public E data; 
    public Node<E> next; 

    public Node(){ 
     data=null; 
     next=null; 
    } 

    public Node(E data1){ 
     data=data1; 
    } 

    public E getData(){ 
     return data;   
    } 

    public Node<E> getNext(){ 
     return next;   
    } 

    @Override 
    public int compareTo(E o) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 
} 

그리고

public class Test { 
    public static void main(String args[]){ 
     ArrayList<Node> arr= new ArrayList<Node>(); 
     Node n1=new Node(1); 
     Node n2=new Node(3); 
     Node n3=new Node(4); 
     Node n4=new Node(3); 
     Node n5=new Node(6); 
     Node n6=new Node(2); 
     arr.add(n1); 
     arr.add(n2); 
     arr.add(n3); 
     arr.add(n4); 
     arr.add(n5); 
     arr.add(n6); 

     Collections.sort(arr); 
    } 
} 

답변

0

을 기본적으로 컬렉션의 E 요소도 비교해야, 다음과 같은 방법으로 적용 할 수있는 :

당신의 Node 클래스 compareTo() 더 신중하게 구현해야 null 데이터 요소를 받아들이는 경우

@Override 
public int compareTo(Node o) { 
    return data.compareTo(o.data); 
} 

:

public class Node<E extends Comparable<E> implements Comparable<Node<E>> { 

지금 compareTo() 당신은 당신의 요소를 비교합니다.

3

신고 내용이 이상하게 보입니다. Node<Integer>Integer을 비교하는 것이 이상 할 것입니다. Node<Integer>과 다른 Node<Integer>을 비교하는 것이 더 합리적입니다.

그러면 두 데이터 값을 비교할 수 있도록 E을 제한해야합니다.

그래서 내가 원하는이 의심 :

public class Node<E extends Comparable<E>> implements Comparable<Node<E>> { 
    ... 
    public int compareTo(Node<E> node) { 
     return data.compareTo(node.data); 
    } 
} 

당신은 이런 복잡성의 비용이 약간 더 유연하게 수 :

public class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> 

(코드의 몸은 동일하게 유지됩니다. ..)

0

기본적으로 의 비교를 런타임 유형 E의 비교에 위임합니다. 따라서 E 자체도 Comparable을 구현해야합니다. 그래서 나는 당신이 의미 생각 :

class Node<E extends Comparable<E>> implements Comparable<Node<E>> { 

    private E data; 

    @Override 
    public int compareTo(Node<E> arg0) {   
     return arg0.data.compareTo(data); 
    } 

} 

은 또한 당신이 E 객체에 Node 객체가 아닌 Node 객체에 Node 개체를 비교해야 있습니다.

옆면 : 반원은 비공개 여야합니다. 당신은 getter도 가지고 있습니다, 그래서 그들은 왜 공개입니까?