如何将未选择的项目从列表移动到另一个列表?列表
How to move unselected items from a List to another? JList
我正在尝试仅将未选中的项目从一个列表移动到另一个列表。另外我想在移动它们之前验证这些项目是否已经在下一个列表中。
这是我目前所拥有的
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" 的项目与 selectedArray 的项目进行比较,但没有成功。
将您的 int[] sel 转换为 Set。这将使添加到新列表之前更容易检查
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));
}
}
现在 secondList 将包含 firstList 中不在 sel 数组索引处的所有元素
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));
}
}
}
我正在尝试仅将未选中的项目从一个列表移动到另一个列表。另外我想在移动它们之前验证这些项目是否已经在下一个列表中。
这是我目前所拥有的
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" 的项目与 selectedArray 的项目进行比较,但没有成功。
将您的 int[] sel 转换为 Set。这将使添加到新列表之前更容易检查
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));
}
}
现在 secondList 将包含 firstList 中不在 sel 数组索引处的所有元素
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));
}
}
}