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 원하는 결과를 얻을 시도했다. comparator 및 Collections.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);
추가 정보는 개체 순서에 튜토리얼을 통해 찾을 수 있습니다 사전에
덕분에
이 나를 위해 일했다. 하지만 라이언의 해결책도 평가할 것입니다. – AKh
이 상황에서 instanceof를 사용하면 안됩니다. 귀하의 '인간'은 내가 [내 대답] (http://stackoverflow.com/questions/7592231/how-to-sort-an-java-util-arraylistparenttype-based-on-html)에서 설명한대로 "유형"을 표현해야합니다. childtype/7592251 # 7592251). –