[英]Compare the first element of each row in 2D array
我想检查每一行的第一个元素(左侧)中的所有匹配元素,如果有匹配项,请在它旁边找到元素。
这是我的示例:
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);
我试图比较2d数组中每一行的第一个元素,以检查是否存在匹配的元素,但是它不能按照我想要的方式工作。
变量和属性数组应输出:
variables stored: [p1, p1, p2, p2]
attribute stored: [boy, girl, girl, boy]
其中第一个元素“ p1”是样本2d数组中紧随其后的“ boy”值。
但是,相反,我的代码决定输出2D数组的全部内容,这是错误的:
variables stored: [hates, p1, p2, hatesCopy, p2, p1]
attribute stored: [hates, boy, girl, hatesCopy, boy, girl]
此外,行的长度各不相同,但列的大小始终为2。关于我要去哪里的问题有什么想法吗?
您正在针对自己检查元素。 只有一个拷贝"hates"
和"hatesCopy"
,但他们对阵自己。
为了防止自我匹配,请添加一个条件以确保a
不等于b
。
if(a != b && sample[b][0].equals(sample[a][0])){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.