java通过整数数组从列表中删除对象?
大家好,我有一个问题,我碰巧在启动时加载了一个对象数组,通过这个数组生成另一个包含代码的整数数组,似乎整数数组正在删除它们的值,我想要的是将当前的整数数组列表与对象数组进行比较,并移除找到整个数组的所有代码对象
我的java代码:
private List<ValidColumnKey> columnCustomer;
private int[] selectedCustomer;
public void init(){
this.setColumnCustomer(new ArrayList<ValidColumnKey>());
this.getColumnCustomer().add(new ValidColumnKey(1, "Codigo", "code"));
this.getColumnCustomer().add(new ValidColumnKey(2, "Nombre", "name"));
this.getColumnCustomer().add(new ValidColumnKey(3, "Nombre Comercial", "comercialName"));
this.getColumnCustomer().add(new ValidColumnKey(4, "Estado", "isActive"));
this.setSelectedCustomer(new int [this.getColumnCustomer().size()]);
int i = 0;
for(ValidColumnKey column : this.getColumnCustomer()){
this.getSelectedCustomer()[i] = column.getCodigo();
i++;
}
}
我的意思是,我将删除带有代码的整数数组,如下所示:
selectedCustomer = [1, 2, 3];
我想从整数数组中没有代码的对象列表中删除,但这不是我的代码:
List<ValidColumnKey> auxRemoColumnKeys = new ArrayList<ValidColumnKey>();
for(ValidColumnKey column : this.getColumnCustomer()){
for(Integer codigo : this.getSelectedCustomer()){
if (column.getCodigo() != codigo) {
auxRemoColumnKeys.add(column);
break;
}
}
}
this.getColumnCustomer().remove(auxRemoColumnKeys);
我可以指导解决方案
# 1 楼答案
您当前的尝试失败有多种原因。首先,这一行:
正在测试
Integer
之间的对象等价性,而不是int
之间的值等价性。如果要比较Integer
,必须使用equals方法:但是,如果
getCodigo
返回一个int
,而getSelectedCustomer
返回一个int[]
,那么这一行应该改为:因为你一开始就不需要使用
Integer
其次,这行代码试图删除auxRemoColumnKeys本身,所以您可能是指
removeAll
:最后,你的逻辑通常是有缺陷的。它基本上说,“对于getColumnCustomer中的每个元素,如果getCodigo不等于getSelectedCustomer的所有元素,请删除它”。我觉得这不是你的本意
这是一个经过修改的循环,使用相同的“添加到列表并删除列表项”过程,但逻辑将起作用:
# 2 楼答案
此语句假定您的类
ValidColumnKey
有一个有效的equals
方法,我怀疑情况可能并非如此您要做的是使用
Iterator
进行迭代。一些示例代码可能是