2017-10-13 4 views
-8

arrayList에서 객체를 정렬하려고합니다. 노드 및 가장자리와 같을 수 있습니다. 예 : I 이런 객체 가지고arrayList에있는 객체를 어떻게 정렬 할 수 있습니까?

Object2 [B, C], 오브젝트 1 [A, B], 오브젝트 4 [E, F를, 오브젝트 4 [C, D, Object5 [F, G

오브젝트 1 [A, B], Object2 [B, C, 오브젝트 4 [C, D :]는 ...

내 질문은이 같은 그룹으로 정렬 할 수 있습니다 방법입니다 ] = Group1 Object4 [E, F], Object5 [F, G] = 그룹 2 ...

어떻게하면됩니까?

+2

은 말 그대로 여러 언어로 각각 정렬 알고리즘의 수십, 그리고 확실하게 구현이있다, 당신은 사용하거나 사용하기 위해 적용 할 수있는 하나 하나를 찾을 수 없습니다? 이는 귀하의 능력이나 노력이 뚜렷하게 부족함을 보여 주며, SO가 사용하고자하는 목적, 즉 구체적인 코딩 질문에 응답하지 않습니다. – AntonH

+0

당신은'Comparable'을 구현할 수 있고, 필요에 따라'compareTo' 메소드를 오버라이드하고'Collections.sort (yourArrayList)'메소드를 호출 할 수 있습니다. 이것은 단지 방법 중 하나 일뿐입니다 ... – assembler

+1

[속성 별 사용자 정의 객체의 정렬 ArrayList] 가능한 복제본 (https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) –

답변

0

사용 대등비교기 아래 그림과 같이, 당신은 또한 자세한 내용은 https://www.journaldev.com/780/comparable-and-comparator-in-java-example를 방문 할 수 있습니다.

import java.util.Comparator; 

    class Employee implements Comparable<Employee> { 

     private int id; 
     private String name; 
     private int age; 
     private long salary; 

     public int getId() { 
      return id; 
     } 

     public String getName() { 
      return name; 
     } 

     public int getAge() { 
      return age; 
     } 

     public long getSalary() { 
      return salary; 
     } 

     public Employee(int id, String name, int age, int salary) { 
      this.id = id; 
      this.name = name; 
      this.age = age; 
      this.salary = salary; 
     } 

     @Override 
     public int compareTo(Employee emp) { 
      //let's sort the employee based on id in ascending order 
      //returns a negative integer, zero, or a positive integer as this employee id 
      //is less than, equal to, or greater than the specified object. 
      return (this.id - emp.id); 
     } 

     @Override 
     //this is required to print the user friendly information about the Employee 
     public String toString() { 
      return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" + 
        this.salary + "]"; 
     } 
} 

Default Sorting of Employees list: [[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]

관련 문제