If I run this operation on List<Integer> for example, it works as expected (removes first 5 elements), but when I run it on a list of my objects, nothing happens (list stays the same).
list.subList(0, 5).clear();
My class is a pojo that doesn't implement equals or hashCode, if that matters.
UPDATE: The implementation I am using is ArrayList, which is returned from Hibernate query. There is nothing to show, really. Sublist doesn't return an empty list.
Here is an example for those who don't beleive it works on a list of Integers:
List<Integer> testList = new ArrayList<Integer>();
for(int i=0;i<10;i++) {
testList.add(i);
}
testList.subList(0, 5).clear();
for(int i=0;i<testList.size();i++) {
System.out.print(testList.get(i)+" ");
}
The result is 5 6 7 8 9
UPDATE2: Actually everything is working as expected, don't know how I couldn't see that (got confused by numbers of results). Sorry for false alarm :) This question could be deleted.
It works on my machinetm
import java.util.*;
import static java.lang.System.out;
class SubListExample {
public static void main( String [] args ) {
List<RandomObject> testList = new ArrayList<RandomObject>();
for(int i=0;i<10;i++) {
testList.add( new RandomObject() );
}
System.out.println( "Before: " + testList );
testList.subList(0, 5).clear();
System.out.println( "After: "+ testList );
}
}
class RandomObject {
static Random generator = new Random();
int id = generator.nextInt(100);
public String toString(){
return "ro("+id+")";
}
}
Produces:
$ java SubListExample
Before: [ro(68), ro(97), ro(48), ro(45), ro(43), ro(69), ro(45), ro(8), ro(88), ro(40)]
After: [ro(69), ro(45), ro(8), ro(88), ro(40)]
So, the problem is not in ArrayList nor in your objects.
I don't think Hibernate returns a plain old ArrayList ( may be it does )
Try printing
System.out.println( "That hibernate list.class.name = "
+ listReturnedByHibernate.getClass().getName() );
And let us know if it is in fact an ArrayList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With