2016-10-14 2 views
-4

Comparator/Comparable 인터페이스를 구현할 수없는 객체의 arraylist가 있습니다.Comparator/Comparable없이 필드로 객체의 ArrayList를 정렬하는 방법

개체의 필드는 정수로 'SequenceNumber'입니다. 내가 언급 한 인터페이스를 구현하지 않고 arraylist를이 필드의 순서 (가장 낮은 것에서 가장 높은 것)로 정렬해야합니다.

쉬운 방법이 있나요? 정렬 알고리즘을 수동으로 쓸 수 있지만 검색 중에 놓친 더 효율적인 (버그없는) 방법이 있는지 궁금하십니까?

참고 : 정렬 처리 할 수있는 비교 클래스를 작성 자바 7

+1

예, 사용 비교기 – ControlAltDel

+0

제가 질문에서 언급 한 바와 같이, 객체가 구현 할 수없는 비교기 – BenParker93

+0

왜 당신이 그 2 인터페이스를 사용하지 않고 정렬해야합니까? 그들은 당신이 정렬 할 수 있도록 설계되었습니다. – Ash

답변

5

사용은 :

private class MyObjectComparator<MyObject> implements Comparator<MyObject> { 

    /** 
    * {@inheritDoc} 
    */ 
    @Override 
    public int compare(MyObject o1, MyObject o2) { 
    return o2.getSequenceNumber() - o1.getSequenceNumber(); 
    } 

} 

그 다음으로 ArrayList를 정렬 :

Collections.sort(myArrayList, new MyObjectComparator()); 
0

당신은에 소개 된 람다 식을 사용할 수 있습니다 Comparable/Comparator 인터페이스를 구현하지 않고 객체를 정렬하는 Java8

다음은 람다를 사용하여 개체를 정렬하고 표시하는 코드 스 니펫입니다.

class Student 
{ 
    int id; 
    String name; 

    public Student(int id, String name) 
    { 
     this.id = id; 
     this.name = name; 
    } 
    public String toString() 
    { 
     return id +" " +name; 
    } 
} 
public class SortDemo 
{ 
    public static void main(String[] args) 
    { 
     List<Student> list=new ArrayList<Student>(); 

     //Adding Objects 
     list.add(new Student(1,"XYZ")); 
     list.add(new Student(3,"ABC")); 
     list.add(new Student(2,"PQR")); 

     System.out.println("Sorting on the basis of name..."); 

     // implementing lambda expression 
     Collections.sort(list,(p1,p2)->{return p1.name.compareTo(p2.name);}); 

     list.forEach((s)->System.out.println(s)); 
    } 
} 
+0

OP는 Java 7을 사용합니다. – Stephan

관련 문제