Alphabetically Sort a Java Collection based upon the 'toString' value of its member items

前端 未结 10 1391
心在旅途
心在旅途 2020-12-29 22:10

Assume I have a user defined Java class called Foo such as:

public class Foo 
{

    private String aField;

    @Override
    public String toString()
    {         


        
10条回答
  •  有刺的猬
    2020-12-29 22:46

    Collections.sort(fooList,
                     new Comparator()
                     {
                         public int compare(Foo f1, Foo f2)
                         {
                             return f1.toString().compareTo(f2.toString());
                         }        
                     });
    

    Assuming that toString never returns null and that there are no null items in the list.

提交回复
热议问题