我正在尝试使用removeAll对ArrayList进行减法操作。但结果并不像预期的那样。实际上它没有删除任何东西。
ArrayList<Integer> tempSelectedPrivilges = new ArrayList<Integer>(privPickList.getTarget());
log.debug("Original selected : " + selectedPrivilges);
log.debug("temp selected : " + tempSelectedPrivilges);
ArrayList<Integer> addedPrivileges = new ArrayList<>(tempSelectedPrivilges);
ArrayList<Integer> deletedPrivileges = new ArrayList<>(selectedPrivilges);
log.debug("Add : " + addedPrivileges);
log.debug("Delete : " + deletedPrivileges);
addedPrivileges.removeAll(selectedPrivilges);
deletedPrivileges.removeAll(tempSelectedPrivilges);
log.debug("Add : " + addedPrivileges);
log.debug("Delete : " + deletedPrivileges);
输出是这样的:
Original selected : [2, 3]
temp selected : [2, 1, 4, 5, 6]
Add : [2, 1, 4, 5, 6]
Delete : [2, 3]
Add : [2, 1, 4, 5, 6]
Delete : [2, 3]
我看到的唯一问题是:
privPickList.getTarget() returns a List<Integer> rather than ArrayList<Integer>.
因为当我创建像这样的tempSelectedPrivileges时,它的工作完全正常:
ArrayList<Integer> tempSelectedPrivilges = new ArrayList<>();
tempSelectedPrivilges.add(3);
tempSelectedPrivilges.add(5);
tempSelectedPrivilges.add(6);
为什么从整数列表创建整数ArayList会产生问题?
当我想要做的时候:
for(Integer i : privPickList.getTarget()) {
tempSelectedPrivilges.add(i);
}
没有编译时错误。但运行时错误
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
在线
tempSelectedPrivilges.add(i);
答案 0 :(得分:0)
适用于我(使用List<Integer>
)在Java 8中正常工作,
public static void main(String[] args) throws Exception {
List<Integer> selectedPrivilges = new ArrayList<>(Arrays.asList(2, 3));
List<Integer> tempSelectedPrivilges = new ArrayList<>(Arrays.asList(2,
1, 4, 5, 6));
System.out.println("Original selected : " + selectedPrivilges);
System.out.println("temp selected : " + tempSelectedPrivilges);
List<Integer> addedPrivileges = new ArrayList<>(tempSelectedPrivilges);
List<Integer> deletedPrivileges = new ArrayList<>(selectedPrivilges);
System.out.println("Add : " + addedPrivileges);
System.out.println("Delete : " + deletedPrivileges);
addedPrivileges.removeAll(selectedPrivilges);
deletedPrivileges.removeAll(tempSelectedPrivilges);
System.out.println("Add : " + addedPrivileges);
System.out.println("Delete : " + deletedPrivileges);
}
输出(正如您所期望的那样)
Original selected : [2, 3]
temp selected : [2, 1, 4, 5, 6]
Add : [2, 1, 4, 5, 6]
Delete : [2, 3]
Add : [1, 4, 5, 6]
Delete : [3]