I've written this generic class as an extension of Arraylist(I know I'm not supposed to do this but I have to). The idea is to add generic objects and sort them. It compiles fine, and when I test it and add an object (from another class) it works fine. However when I add a second object, the program waits for about 30 seconds then returns "java.lang.outofmemory error out of heap space".
import java.util.ArrayList;
import java.util.*;
/**
* extending to ArrayList
*/
public class SortedArrayList<E extends Comparable> extends ArrayList<E>
{
/**
* Constructing the super
*/
public SortedArrayList()
{
super();
}
public void insertAndSort (E element){
if (isEmpty()){
add(element);
}
for ( int i = 0; i < size(); i++){
E otherElement = get(i);
if(element.compareTo(otherElement) > 0){
add(i, element);
}
if(element.compareTo(otherElement) < 0) {
add(i+1, element);
}
}
}
}
Can anyone see why this is happening? Is there something wrong with my for loop? Thanks
Your insert
method is off. You need to find the correct position and add the element, not add the element for every element in the current List
.
public void insertAndSort(E element) {
if (isEmpty()) {
add(element);
return;
}
int len = size();
int pos = 0;
while (pos < len && element.compareTo(get(pos)) > 0) {
pos++;
}
add(pos, element);
}
and the generic should be applied to Comparable
. So this
SortedArrayList<E extends Comparable>
should be
SortedArrayList<E extends Comparable<E>>