Java:为什么subList(0,5).clear()不能对我的对象起作用?

ser*_*erg 1 java collections

List<Integer>例如,如果我运行此操作,它按预期工作(删除前5个元素),但是当我在我的对象列表上运行它时,没有任何反应(列表保持不变).

list.subList(0, 5).clear();
Run Code Online (Sandbox Code Playgroud)

我的班级是一个没有实施的pojo,equals或者hashCode如果重要的话.

更新: 我使用的实现是ArrayList,它是从Hibernate查询返回的.真的没有什么可以表现出来的.子列表不返回空列表.

这是一个例子,对于那些不相信它在整数列表上工作的人:

    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)+" ");
    }
Run Code Online (Sandbox Code Playgroud)

结果是 5 6 7 8 9

UPDATE2:实际上一切都按预期工作,不知道我怎么看不到(被结果数量搞糊涂了).抱歉误报:)这个问题可以删除.

Osc*_*Ryz 5

它适用于我的机器tm

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+")";
    }
}
Run Code Online (Sandbox Code Playgroud)

生产:

$ 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)]
Run Code Online (Sandbox Code Playgroud)

所以,问题不在ArrayList你的对象中.

我认为Hibernate回归不是很平常ArrayList(可能是这样)

尝试打印

 System.out.println( "That hibernate list.class.name = "
        + listReturnedByHibernate.getClass().getName() );
Run Code Online (Sandbox Code Playgroud)

如果它实际上是一个,请告诉我们 ArrayList