我想检查每行第一个元素(左侧)中的所有匹配元素,如果匹配,请获取它旁边的元素。比较2D数组中每一行的第一个元素
这里是我有作为一个例子:
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);
我试图比较二维数组中的每一行的第一个元素,以检查是否存在一个匹配的元素,但它不工作我想要的方式。
的变量和属性阵列应该输出:
variables stored: [p1, p1, p2, p2]
attribute stored: [boy, girl, girl, boy]
当第一元件“P1”是下一个从样品2D阵列它“男孩”的值。
但是,相反,我的代码,就决定输出二维数组这是不对的整个事情:
variables stored: [hates, p1, p2, hatesCopy, p2, p1]
attribute stored: [hates, boy, girl, hatesCopy, boy, girl]
此外,该行的长度发生变化,但列将永远是2的大小。 关于我要去哪里的任何想法都是错误的?
'sample'是一个2D数组,但您正在检查'sample [b] .equals(sample [a])''。这比较了1D数组,而不是String元素。你需要两个索引来获取一个元素(例如'sample [b] [c]')。 – collinjsimpson
是的,我试过使用样本[b] [0] .equals(样本[a] [0]),只输出:变量存储:[hates,p1,p1,p2,p2,hatesCopy,p2,p2,p1,p1 ] 属性存储:[恨,男孩,女孩,女孩,男孩,恨,复制,女孩,男孩,男孩,女孩] – user3273108