2017-10-13 97 views
-8

我想排序arrayList中的對象。可能像節點和邊緣。 例如:我有這樣的對象:我如何排序arrayList中的對象?

Object2的[B,C],Object1 [A,B],Object4 [E,F],Object3 [C,d], Object5 [F,G ] ...

我的問題是我怎麼能歸類到組這樣的:

Object1 [A,B],對象2 [B,C],Object3 [C,d ] = Group1 Object4 [E,F], Object5 [F,G] = Group2 ...

我該怎麼辦?

+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]]