我的大脑有点酸痛,我不知道为什么这行不通。
我有两个数组列表
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> name2 = new ArrayList<String>();
我需要检查“name”中的值是否包含“name2”中的值,如果是,则进行迭代,这是我当前的代码:
private ArrayList<Integer> getForeignKey() {
ArrayList<Integer> foreignKey = new ArrayList<Integer>();
for (int i = 0; i < name.size(); i++) {
int intForeignKey = 1;
for (int x = 0; x < name2.size(); x++)
//System.out.println(name.get(i) + " ---------------- " + name2.get(x));
if (!name.get(i).contains(name2.get(x)))
intForeignKey++;
else
break;
foreignKey.add(intForeignKey);
}
return foreignKey;
}
当打印出来时,它对于几个值来说可以正常工作,然后它开始跳过数字,所以输出将是:
0
1
2
3
4
5
5
10
当它应该是
0 1 3 4 5 5 6 7 8 8 8 9 10
我做错了什么?如果需要更多澄清,我会尽力。
编辑:
请注意,上面的数字只是输出的示例数字。
名称包含:
a,b,c,d,e,f,g
名称2包含
a,b,c,c,d,e,e,f,g,g
name(index i) 检查它是否包含 name2(index x) 值,如果包含该值,则不增加外键整数,如果不包含该值,则增加外键整数。
最佳答案
您是否想查找两个集合中相同的名称?
private final Set<String> names = new LinkedHashSet<String>();
private final Set<String> names2 = new LinkedHashSet<String>();
public Set<String> namesInBoth() {
Set<String> ret = new LinkedHashSet<String>(names);
ret.retainAll(names2);
return ret;
}
关于java - 如何使用java比较数组列表中的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6306936/