I have a list of object to sort alphabetically on an attribute. I can't override the equals method on this object because it's a generated class, my implementation will be deleted during th开发者_如何学JAVAe next generation. I think I will implement this sort in a toolbox class. Is there a way to not reinvent the wheel?
Use custom Comparator
class A{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public A() {
    }
    public A(String name) {
        this.name = name;
    }
}
List<A> aList = new ArrayList<A>();
aList.add(new A("abc"));
aList.add(new A("sda"));
aList.add(new A("aaa"));
Collections.sort(aList,new Comparator<A>() {
            public int compare(A o1, A o2) {
                return o1.getName().compareTo(o2.getName());
            }
});
Something like:
class Foo {
    public String field;
}
public static void main(String[] args) {
    List<Foo> foos = new ArrayList<Foo>();
            ....        
    Collections.sort(foos, new Comparator<Foo>() {
        @Override
        public int compare(Foo o1, Foo o2) {
            return o1.field.compareTo(o2.field);
        }
    });
}
You may have a look at the API. You only need to implement the comparator to compare your attributes
you can use comparator, let's says you are sorting a list (myList) of Person with their alphabetical name (getName()).
List<Person> myList = new ArrayList<Person>(keys);
Collections.sort(myList, new Comparator<Person>() {
  @Override
  public int compare(Person p1, Person p2) {
    String s1 = p1.getName();
    String s2 = p2.getName();
    return s1.compareTo(s2);
  }     
}); 
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论