Search code examples
javaarraylistserializablecomparable

Order ArrayList serializable


I have two class in JAVA:

public class Persons implements Serializable{
    String name;
    String phone;

    ...
}

and:

public class Diary implements Comparable{
    ArrayList<Persons> persons=new ArrayList();

    ...
}

I want to order my ArrayList by the name (in alphabetical), but I can't use Collections.sort() because my ArrayList is Persons class and this give me and error. I can't implements Comparable in class Persons because if i do it, i can't read later my ArrayList which is save in a Object .dat


Solution

  • try this

        Collections.sort(persons, new Comparator<Persons>() {
            @Override
            public int compare(Persons o1, Persons o2) {
                return o1.name.compareTo(o2.name);
            }});