java - alphabetically sort elements in a List -
this question has answer here:
i have shape
class , in class there method called getrepr()
can char
representation of shape. example,
shapea.getrepr() ->'a' shapeb.getrepr() ->'b' shapec.getrepr() ->'c'
now have arraylist
stores several shapes including shapee
, shapea
, shaped
, shapec
, , shapeb
.
the question how can use collections.sort()
alphabetically rearrange these shapes in arraylist
according char
representations?
the expected result in arraylist
after sorting should shapea
, shapeb
, shapec
, shaped
, shapee
.
or there way reach purpose without collections.sort()
?
you need implement comparable interface in superclass
public class myclasssuperclass implements comparable<myclasssuperclass>{ @override public int compareto(myclasssuperclass o) { return this.getrepr().compareto(o.getrepr()); } }
then can call .sort method on collection
- if obj a>b compareto shall return value > 0
- if obj
- if obj == b compareto shall return 0
for mathematically inclined, relation defines natural ordering on given class c is:
{(x, y) such x.compareto(y) <= 0}. quotient total order is: {(x, y) such x.compareto(y) == 0}. follows contract compareto quotient
equivalence relation on c, , natural ordering total order on c. when class's natural ordering consistent equals, mean quotient natural ordering equivalence relation defined class's equals(object) method: {(x, y) such x.equals(y)}.
for more information please check link:
https://docs.oracle.com/javase/7/docs/api/java/lang/comparable.html