I have the following method that accepts a generic object (When I use it, I pass an Integer Object) and removes the object at that position in the array. Note that my
private currentSize;
private E[] list;
...
public E remove(E obj){
for (int i = 1; i < currentSize; i++)
if( ((Comparable<E>)obj).compareTo(list[i]) == 0){
for(int j = i; j < currentSize; j++)
list[j] = list[j+1];
currentSize--;
return obj;
}
return null;
}
I have two other methods that relate to my method above.
for(int i=1; i <= 10; i++)
list.addLast(i);
The code above adds 10 sequential ints to my array. (This works perfectly. Note that the addLast method parses only a primitive int, because I have it declared like so in addLast() )
for(int i=1; i <= 10; i++){
list.remove(new Integer(i));
}
The code above removes those 10 ints we added before. My remove() method kind of works, it removes all Integer Objects from the array except 1.
My output when I call both addLast and then remove methods in another class:
"1 2 3 4 5 6 7 8 9 10
Now removing them all Current size of list: (should be zero) 1"
That one in front of (should be zero) is not supposed to be there. Please note that I am trying to ignore the 0 index of the array. Also, I would like to know the way of implementing a backwards implementation of my inner-most for loop for(int j = i; j < currentSize; j++)
. Sort of like [1,2,3,4,5] ... if I want to "remove" #2 in the array, I would start from the end of the array instead of the beginning.
Thank you for you help in advance!
EDIT:
addLast method code:
public void addLast(E obj){
list[currentSize++] = obj;
//System.out.println(currentSize);
}
Print all the objects in array:
for(int x : list)
System.out.print(x + " ");
System.out.println("\n");
Aucun commentaire:
Enregistrer un commentaire