89 lines
1.8 KiB
Java
89 lines
1.8 KiB
Java
package org.hwo.collections;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Iterator;
|
|
import java.util.List;
|
|
|
|
public class SortedList<T extends Comparable<T>> implements Iterable<T>{
|
|
|
|
private List<T> backingStore;
|
|
|
|
public SortedList(){
|
|
this.backingStore = new ArrayList<T>();
|
|
}
|
|
|
|
public SortedList(List<T> backingStore){
|
|
this.backingStore = backingStore;
|
|
}
|
|
|
|
public T after(T element){
|
|
for (int i=0;i<backingStore.size();i++){
|
|
//System.err.format("after(): compare = %d\n", backingStore.get(i).compareTo(element));
|
|
if (backingStore.get(i).compareTo(element) > 0)
|
|
return backingStore.get(i);
|
|
}
|
|
return null;
|
|
}
|
|
public T before(T element){
|
|
for (int i=backingStore.size();i>0;i--){
|
|
if (backingStore.get(i-1).compareTo(element) < 0)
|
|
return backingStore.get(i-1);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
public boolean add(T element){
|
|
if (backingStore.contains(element))
|
|
return false;
|
|
|
|
T a = after(element);
|
|
if (a == null){
|
|
System.err.println("a == null");
|
|
return backingStore.add(element);
|
|
}
|
|
System.err.println(String.format("Add: %d", backingStore.indexOf(a)));
|
|
backingStore.add(backingStore.indexOf(a), element);
|
|
return true;
|
|
}
|
|
|
|
public void clear(){
|
|
this.backingStore.clear();
|
|
}
|
|
|
|
public boolean remove(T element){
|
|
return backingStore.remove( element );
|
|
}
|
|
public boolean remove(int index){
|
|
return backingStore.remove( backingStore.get(index));
|
|
}
|
|
|
|
public int indexOf(T element){
|
|
return this.backingStore.indexOf(element);
|
|
}
|
|
|
|
public T get(int index){
|
|
return backingStore.get(index);
|
|
}
|
|
|
|
public boolean contains(T element){
|
|
return backingStore.contains(element);
|
|
}
|
|
|
|
public Object[] toArray(){
|
|
return backingStore.toArray();
|
|
}
|
|
|
|
public T[] toArray(T[] a){
|
|
return backingStore.toArray(a);
|
|
}
|
|
|
|
@Override
|
|
public Iterator<T> iterator() {
|
|
return backingStore.iterator();
|
|
}
|
|
|
|
|
|
|
|
}
|