I want to check all matching elements in the first element (left side) of each row, and if there's a match, get the elements next to it.
我想检查每一行的第一个元素(左侧)中的所有匹配元素,如果匹配,则获取它旁边的元素。
Here's what I have got as an example:
以下是我的例子:
ArrayList<String> variables = new ArrayList<String>();
ArrayList<String> attribute = new ArrayList<String>();
String[][] sample = { {"hates", "hates"},
{"p1","boy"},
{"p2","girl"},
{"hatesCopy", "hatesCopy"},
{"p2","boy"},
{"p1","girl"}};
for(int a = 0; a < sample.length; a++){
for(int b = 0; b < sample.length; b++){
if(sample[b].equals(sample[a])){
variables.add(sample[b][0]);
attribute.add(sample[b][1]);
}
}
}
System.out.println("variables stored: "+ variables);
System.out.println("attributes stored: "+ attribute);
I have tried to compare the first element of each row in the 2d array to check if there exists a matching element, but it isn't working the way I want it to.
我试图比较2d数组中每行的第一个元素,以检查是否存在匹配元素,但它不能按照我想要的方式工作。
The variables and attributes array should output:
变量和属性数组应该输出:
variables stored: [p1, p1, p2, p2]
attribute stored: [boy, girl, girl, boy]
Where the first element "p1" is value next to it "boy" from the sample 2d array.
其中第一个元素“p1”是样本2d数组中“boy”旁边的值。
But instead, my code decides to output the entire thing of the 2D array which is wrong:
但相反,我的代码决定输出错误的2D数组的整个内容:
variables stored: [hates, p1, p2, hatesCopy, p2, p1]
attribute stored: [hates, boy, girl, hatesCopy, boy, girl]
Also, the length of the row varies, but the column will always be the size of 2. Any ideas on where I am going wrong?
此外,行的长度各不相同,但列总是大小为2.任何关于我出错的想法?
1 个解决方案
#1
1
You are checking elements against themselves. There is only one copy of "hates"
and "hatesCopy"
, but they match against themselves.
你正在检查自己的元素。只有一个“讨厌”和“hatesCopy”的副本,但它们与自己匹配。
To prevent self matches, add a condition to make sure a
doesn't equal b
.
要防止自我匹配,请添加条件以确保a不等于b。
if(a != b && sample[b][0].equals(sample[a][0])){
#1
1
You are checking elements against themselves. There is only one copy of "hates"
and "hatesCopy"
, but they match against themselves.
你正在检查自己的元素。只有一个“讨厌”和“hatesCopy”的副本,但它们与自己匹配。
To prevent self matches, add a condition to make sure a
doesn't equal b
.
要防止自我匹配,请添加条件以确保a不等于b。
if(a != b && sample[b][0].equals(sample[a][0])){