My brain in kind of sore and I can't put a finger on why this wouldn't work.
I have two arraylist
private ArrayList<String> name = new ArrayList<Stri开发者_Go百科ng>();
private ArrayList<String> name2 = new ArrayList<String>();
I need to check if the value in 'name' contains the value in 'name2' and if it is, iterate, here is my current code for this:
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;
}
When this is printed out it will work fine for a couple of values, then it starts skipping numbers, so the output would be:
0
1
2
3
4
5
5
10
when it's suppose to be
0 1 3 4 5 5 6 7 8 8 8 9 10
What am I doing wrong? If more clarification is needed, I will try my best.
EDIT:
Please note that the numbers above are just example number of what the output should look like.
name contains:
a,b,c,d,e,f,g
name2 contains
a,b,c,c,d,e,e,f,g,g
name(index i) checks if it contains the name2(index x) value, if it contains the value do NOT increment the foreign key integer, if it does not contain the value then increment the foreign key integer.
Are you trying to find the names which are the same in both collections?
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;
}
I'm not sure why this isn't working (what's in name
and name2
?). A much better way to do this, though, is to use a HashSet to store the unique names and then extract them into an ArrayList.
Possible error - you use .contains to compare Strings. You should use .equals or .equalsIgnoreCase instead.
EDIT:
private ArrayList<Integer> getForeignKey() {
ArrayList<Integer> foreignKey = new ArrayList<Integer>();
for (int i = 0; i < name.size(); i++) {
boolean found = false;
for (int x = 0; x < name2.size(); x++){
if (name.get(i).equals(name2.get(x))){
found = true;
break;
}
}
if(!found){
foreignKey.add(i);
}
}
return foreignKey;
}
精彩评论