我需要将列表中的值与数组中的值进行比较。 我写了以下内容:
public class JavaApplication3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
我得到以下信息 0,测试,测试, c,c,1 但我需要这样的结果: 0、c、1、
最佳答案
看看你的预期结果,我猜要求是这样的:
对于数组中的每个元素,检查它是否在列表中。如果它在列表中,则打印该元素在列表中的索引,否则打印该元素本身。所以算法应该这样做:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
外部循环应该迭代数组。然后,对于每个数组项,迭代列表,直到找到相同的元素。对于初稿,不要将输出收集在字符串中,而是立即打印。当算法按预期工作时,您可以创建字符串。
关于java - 比较列表和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17476490/