I want to order a list every time a new element is added. My approach is to override the add method and add the sorting of my list. But I think this looks funny. Is their a better way to do this?
public class Test extends TestCase {
List<String> superlist = new ArrayList<String>() {
private static final long serialVersionUID = 1L;
public boolean add(String e) {
boolean erg = super.add(e);
Comparator<String> comp = (o1, o2) -> {
return o1.compareTo(o2);
};
Collections.sort(this, comp);
return erg;
};
};
public void test() {
superlist.add("A");
superlist.add("Z");
superlist.add("D");
superlist.add("X");
superlist.add("C");
System.out.println(superlist); // [A, C, D, X, Z]
}
}
Update You could write a class, that extends ArrayList and compare every time a element is added. I think that's nicer