2011-09-29 1 views
4
public interface Human<T> extends Comparable<T>{ } 

public class Men implements Human<Men>{ 
    public Men(String firstName) { 
    this.firstName = firstName; 
    } 
..... 
} 

public class Women implements Human<Women>{ 
public Women(String firstName) { 
    this.firstName = firstName; 
    } 
..... 
} 

public class MainTest{ 

    public static void main(String[] args) { 

     List<Human> engineers= new ArrayList<Human>(); 
     engineers.add(new Men("A")); 
      engineers.add(new Women("A")); 
     engineers.add(new Men("C")); 
     engineers.add(new Men("E")); 
     engineers.add(new Men("Z")); 
      engineers.add(new Women("J")); 
     engineers.add(new Women("B")); 
     engineers.add(new Men("X")); 
     engineers.add(new Men("O")); 
     engineers.add(new Women("G")); 

     Collections.sort(engineers); 

     System.out.println(.... print the engineers array...) 
} 

출력java.util.ArrayList를 정렬하는 방법 <ParentType> ChildType을 기반으로 하시겠습니까?

남성 (A); 남자 (C); 남자 (E); 나없이); 남자 (X); 남자 (Z) 여자 (A); 여성 (B); 여성 (G); 여성 (AJ);

내 정렬 된 arraylist는 initially sorted in terms of the TYPE (Men or Women) and the secondary sort is based on firstname이어야합니다. 이걸 어떻게 잘 수행 할 수 있습니까?

은 내가 Collections.sort(....)

을 couldnt 원하는 결과를 얻을 시도했다. comparatorCollections.sort(List l, Comparator c)

static final Comparator<Human> MyComparator = 
           new Comparator<Human>() 
{ 
    public int compare(Human e1, Human e2) 
    { 
      // Your custom comparison code goes here 
    } 
}; 

Collections.sort(engineers, MyComparator); 

추가 정보는 개체 순서에 튜토리얼을 통해 찾을 수 있습니다 사전에

덕분에

답변

3

당신은 아마 의미

public interface Human extends Comparable<Human> {} 

즉 : 인간은 다른 인간과 비교할 수 있습니다. 유형과 이름을 모두 취할 다음 compareTo()의 적절한 구현을 작성

public interface Human extends Comparable<Human> { 
    enum Type { MAN, WOMAN } 
    Type getType(); 
    String getName(); 
} 

: 당신의 이름 뒤에 유형에 따라 인간을 비교하려는 경우 즉되는 경우, 다음 인터페이스 인간은 이러한 속성을 모두 표현하기 위해 필요 을 고려하여 Collections.sort()을 사용하여 정렬 할 수 있습니다.

0

"Comparator"인터페이스를 사용하는 것이 좋습니다.
이 인터페이스를 구현하는 다른 클래스를 작성하십시오.
그런 다음 비교 메소드에서 인스턴스를 확인한 다음 인스턴스의 구성원을 확인하는 적절한 코드를 작성하십시오.

1

너희들이 추천하고 있니?

public class HumanComparator implements java.util.Comparator<HumanBeings> { 

    @Override 
    public int compare(HumanBeings o1, HumanBeings o2) { 
     if(o1 instanceof Men && o2 instanceof Men) 
      return 0; 
     else if(o1 instanceof Men && o2 instanceof Women) 
      return -1; 
     else if (o1 instanceof Women && o2 instanceof Men) 
      return 1; 

     return 0; 

    } 
} 

.... 더 많은 코드를 추가로 더 종류의 ... FIRSTNAME에 의해

+0

이 나를 위해 일했다. 하지만 라이언의 해결책도 평가할 것입니다. – AKh

+0

이 상황에서 instanceof를 사용하면 안됩니다. 귀하의 '인간'은 내가 [내 대답] (http://stackoverflow.com/questions/7592231/how-to-sort-an-java-util-arraylistparenttype-based-on-html)에서 설명한대로 "유형"을 표현해야합니다. childtype/7592251 # 7592251). –

2

비교기 구현 based on Ryan Stewart's solution. 위대한 작품!

Collections.sort(engineers, new Comparator<Human>() { 
    @Override 
    public int compare(Human o1, Human o2) { 
     if(o1.getType().equals(o2.getType())) { 
      return o1.getFirstName().compareTo(o2.getFirstName()); 
     } else { 
      return o1.getType().compareTo(o2.getType()); 
     } 
    } 
}); 
2
class HumanComparator implements Comparator<Human>{ 

@Override 
public int compare(Human humanObj1, Human humanObj2) { 
    int index; 
    if(humanObj1 instanceof Men && humanObj2 instanceof Men){ 
     String firstName1 = humanObj1.getFirstName(); 
     String firstName2 = humanObj2.getFirstName(); 
     index = firstName1.compareTo(firstName2); 
    }else if(humanObj1 instanceof Women && humanObj2 instanceof Women){ 
     String firstName1 = humanObj1.getFirstName(); 
     String firstName2 = humanObj2.getFirstName(); 
     index = firstName1.compareTo(firstName2); 
    }else if(humanObj1 instanceof Men && humanObj2 instanceof Women){ 
     index =-1; 
    }else if(humanObj1 instanceof Women && humanObj2 instanceof Men){ 
     index =+1; 
    }else{ 
     index =0; 
    } 
    return index; 
} 

}

와 아래 사용하여 컬렉션을 정렬 할 수 있습니다

Collections.sort(engineers ,new HumanComparator()); 
관련 문제