Skip to content

Instantly share code, notes, and snippets.

@kingsamadesu
Created December 8, 2020 15:44
Show Gist options
  • Save kingsamadesu/62af49b05f92bfb2f3ff915f21c32452 to your computer and use it in GitHub Desktop.
Save kingsamadesu/62af49b05f92bfb2f3ff915f21c32452 to your computer and use it in GitHub Desktop.
SortedList Implementation using ArrayList in java,
//there is no List collection in java that keeps its elements sorted, and provides imidiat sorting while inserting element
//So this is a simple essay to adjust the add() method to keep the collection sorted after add an element.
//this simple essay keeps all ArrayList methods usable,
//if you want to sort a collection what ever is it you can just pass it as a parameter to the constructor
//package Mypakage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class SortedList<E> extends ArrayList{
public SortedList() {
super();
}
public SortedList(Collection c) {
super(c);
Collections.sort(this);
}
@Override
public boolean add(Object o) {
boolean test = super.add(o);
Collections.sort(this);
return test;
}
@Override
public boolean addAll(Collection c) {
boolean test = super.addAll(c);
Collections.sort(this);
return test;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment