0
List<Left> resultList = lists.iterator().next();
    for (Iterator iterator = lists.iterator(); iterator.hasNext();) {
        List<Left> list = (List<Left>) iterator.next();         
        resultList.retainAll(list);
    }

    /*for (Left left : resultList) {
         System.out.println(left.getData());
    }*/

    for (Left left : mLeft) {           
        ArrayList<Left> mTempList = left.getArray();    
        for (Iterator iterator = mTempList.iterator(); iterator.hasNext();) {
            Left left2 = (Left) iterator.next();
            System.out.println(left2.getData());
        }
    }

我试图找出共同的元素,我的原始列表正在改变。我的意思是当我打印列表时只有最后一个元素被改变。有什么建议么。

4

1 回答 1

1

resultList gets assigned to the first element in your collection lists right at the top.

On line 4 you execute retainAll against resultList without changing what resultList is assigned to - it's still pointing to the first object in lists.

You might consider creating a new List<Left> object to check for the common elements, right at the start instead of how you've declared resultList:

List<Left> resultList = new List<Left>();
resultList.addAll ((List<Left>) lists.iterator().next());
...

You would then want to use resultList in the final loop when you print out the elements.

Note that you are still assuming that lists has at least one element - if it's empty you'll get an exception.

于 2012-04-25T04:45:15.460 回答