Dave's Brain

Browse - Programming Tips - How can I make my class work with Collections.sort() ?

Date: 2016mar12
Language: Java
Keywords: Comparator

Q.  How can I make my class work with Collections.sort() ?

A.  Implement Comparable like this:

import java.util.Collections; import java.lang.Comparable; import java.util.ArrayList; class MyEntry implements Comparable<MyEntry> { String member1;
@Override int compareTo(CompanyEntry b) { return member1.compareTo(b.member1); } } void exampleUse() { ArrayList<MyEntry> a = new ArrayList<MyEntry>(); // Add things to the array Collections.sort(a); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.