[英]Remove objects from a list through an array of integers?
嗨,社區,我有一個問題,我碰巧在啟動時加載了一個對象數組,通過該對象生成另一個包含您的代碼的整數數組,看來該整數數組正在刪除其值,我想要比較的是當前具有對象數組的整數數組列表,並刪除找到整個數組提到的所有代碼對象。
我的代碼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);
我可以指導解決方案。
this.getColumnCustomer().remove(auxRemoColumnKeys);
該語句假定您對類ValidColumnKey
具有有效的equals
方法,我懷疑情況可能並非如此。
您要做的是使用Iterator
進行Iterator
。 一些示例代碼可能像
Set<Integer> toRemoveCodes = new HashSet<Integer>(Arrays.asList(1, 2, 3));
for (Iterator<ValidColumnKey> it = this.getColumnCustomer().iterator(); it.hasNext(); ) {
ValidColumnKey curColumnKey = it.next();
Integer code = curColumnKey.codigo();
if (toRemoveCodes.contains(code)) {
it.remove();
}
}
當前嘗試失敗有多種原因。 首先是這一行:
if (column.getCodigo() != codigo) {
正在測試Integer
之間的對象等效性,而不是int
之間的值等效性。 如果要比較Integer
,則必須使用equals方法:
if (!column.getCodigo().equals(codigo)) {
但是,如果getCodigo
返回一個int
且getSelectedCustomer
返回一個int[]
則應改為以下行:
for(int codigo : this.getSelectedCustomer()){
因為您一開始不需要使用Integer
。
其次,此行嘗試刪除auxRemoColumnKeys本身,因此您可能是指removeAll
:
this.getColumnCustomer().remove(auxRemoColumnKeys);
最后,您的邏輯通常存在缺陷。 它基本上說: “對於getColumnCustomer中的每個元素,如果getCodigo不等於所有getSelectedCustomer,則將其刪除” 。 我認為這不是您想要的。
這是一個修改后的循環,使用相同的“添加到列表並刪除列表項”過程,但邏輯將起作用:
List<ValidColumnKey> auxRemoColumnKeys = new ArrayList<ValidColumnKey>();
int[] selected = this.getSelectedCustomer();
for (ValidColumnKey column : this.getColumnCustomer()) {
int i = 0;
for ( ; i < selected.length; i++) {
/* note: if getCodigo returns an Integer change this check to
* "if (column.getCodigo().equals(selected[i])) {"
*/
if (column.getCodigo() == selected[i]) {
break;
}
}
/* this says "if the search loop did not break early" */
if (i == selected.length) {
auxRemoColumnKeys.add(column);
}
}
this.getColumnCustomer().removeAll(auxRemoColumnKeys);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.