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

前端 未结 10 1457
心在旅途
心在旅途 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:48

    public class Foo
       implements Comparable
    {
    
        private String aField;
    
        public Foo(String s)
           {
           aField=s;
            }
    
    
        public String getAField()
            {
            return aField;
            }
    
       public int compareTo(Foo other)
            {
            return getAField().compareTo(other.getAField());
            }
    
    
        @Override
        public String toString()
        {
        return getAField();
        }
    
    }
    

    and then

    Collections.sort(list);

提交回复
热议问题