1

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Jackel
  • 23
  • 5
  • Java collections do not, AFAIK, support any sorted list. But, there is a sorted set. Why do you think that a list is the best data structure for your problem? – Tim Biegeleisen Oct 22 '19 at 08:31
  • I choose a list because i have dublicated entries and i want to distinguish between the implementation [A, C, D, X, Z] and [A, A, C, D, X, Z]. And i think a sorted set is also a collection: [Link 3317381](https://stackoverflow.com/questions/3317381/what-is-the-difference-between-collection-and-list-in-java) – Jackel Oct 22 '19 at 11:00
  • Possible duplicate of [Why is there no SortedList in Java?](https://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java) The accepted answer explains why it doesn't exist and presents several different ways to implement it yourself. – John Kugelman Nov 12 '19 at 16:17

0 Answers0