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

前端 未结 10 1453
心在旅途
心在旅途 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 23:06

    I would do something very similar to Pierre:

    public class Foo implements Comparable
    {
        private String aField;
    
        @Override
        public String toString()
        {
            return aField;
        }
    
        public int compareTo(Foo o)
        {
            return this.toString().compareTo(o.toString());
        }
    }
    

    Then, like Pierre, I would use Collections.sort(list) as Pierre suggests.

提交回复
热议问题