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

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

    I would strongly advise you to only use toString for debugging purposes... however... to expand on what Yuval A wrote above...

    public class X
        implements Comparator
    {
        public int compare(final Foo a, final Foo b) 
        {
            return (a.toString().compareTo(b.toString()));
        }
    }
    

    However you really should have Foo implement Comarable or write a proper Compartor that does not make use of toString.

提交回复
热议问题