[英]How to move unselected items from a List to another? JList
I'm trying to move only the unselected items from a List into another List. 我正在尝试仅将一个列表中未选中的项目移动到另一个列表中。 Also I would like to validate if the items are already on the next list before moving them.
另外,我想在移动它们之前验证这些项目是否已经在下一个列表中。
This is what I have so far 这就是我到目前为止
int sel[] = lstNum1.getSelectedIndices();
for (int i = 0; i < model1.getSize(); i++) {
if(!model1.getElementAt(i).equals(model1.getElementAt(sel[i]).toString())){
model2.addElement(model1.getElementAt(i).toString());
}
}
I'm trying to compare the item at position "i" with the item at the selectedArray, but no luck. 我正在尝试将位置“ i”的项目与selectedArray的项目进行比较,但是没有运气。
A simpler version of the answer provided by AbtPst: AbtPst提供的答案的简单版本:
Set<Integer> keepThese = new HashSet<Integer>();
for (int x : sel) {
keepThese.add(x);
}
for (int i=0 ; i<firstList.size() ; i++) {
if( !keepThese.contains(i)) {
if( !secondList.contains(firstList.get(i))) {
secondList.add(firstList.get(i));
}
}
}
convert your int[] sel to a Set. 将您的int [] sel转换为Set。 this will make it easy to check before adding to new list
这将使在添加到新列表之前易于检查
Set<Integer> keepThese = new HashSet<Integer>();
for (int x : sel)
{
keepThese.add(x);
}
for (int i=0 ; i<firstList.size() ; i++)
{
if(keepThese.contains(i))
continue;
else
{
if(secondList.contains(firstList.get(i)))
continue;
else
secondList.add(firstList.get(i));
}
}
now secondList will have all the elements from firstList that are not at indices in the sel array 现在secondList将具有firstList中所有不在sel数组中的索引处的元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.