在Java中将2d数组与1d进行比较

时间:2011-11-04 21:29:31

标签: java

伙计我在使用java方面有点新,我正在尝试编写一个程序来检查2d数组,如果它包含1d数组的值。第二个数组就像一个数字列表,它会检查第一个数组如果匹配。

array1[6]= {"a","b","c","d","e","f"}
array2[1][4]={{"a","b","c","d"}{"d","e","f","g"}}
array2[0]= rowcomplete ; // because it contain all the value a,b,c,d
array2[1]= incomplete; // because it only match d,e,f but not g

这是我的代码:

String array1[] = {"a","b","c","d","e","f"};
String array2[][] = {{"a","b","c","d"}, {"d","e","f","g"}};

for (int 2row = 0; 2row < array2.length; 2row++) {
  for (int 2column = 0;2column< array2[2row].length;2column++) {    
    for(int 1row=0; 1row < array1[1row].length();1row++) {
      if (array2[2row][2column].equals(array1[1row])) {
        System.out.println("complete"); 
      }
      else{

      }
    }
  }
}

4 个答案:

答案 0 :(得分:3)

一种简单的方法是使用Arrays类将数组转换为List并使用containsAll方法,如下所示:

  String array1 []={"a","b","c","d","e","f"};
  String array2 [][] ={{"a","b","c","d"},{"d","e","f","g"}};

  List<String> array1AsList = Arrays.asList(array1);

  for (int i = 0; i < array2.length; i++) {
      List<String> array2rowAsList = Arrays.asList(array2[i]);

      if(array1AsList.containsAll(array2rowAsList)){
          System.out.println("row " + i + " is complete");
      }
  }

答案 1 :(得分:2)

只是为了澄清班塔尔上面的评论意味着什么:

Java变量名称不能以数字开头。它们只能以_underscore,字母或美元符号$开头。在第一个字母后,您可以使用数字。

答案 2 :(得分:2)

如果对array1使用数组列表,这会更容易,因为您可以使用arrayList.contains()来确定值是否在列表中。

使用数组列表并像之前一样声明/初始化array2,试试这个:     ArrayList array1 = new ArrayList();     Collections.addAll(array1,“a”,“b”,“c”,“d”,“e”,“f”);
    boolean matchFlag;

for(int i = 0;i< array2.length; i++){
    matchFlag = true;
    for(int j=0;j<array2[i].length; j++){
        if(array1.contains(array2[i][j]) == false){
            //found string that did not match
            //
            matchFlag = false;
        }
    }
    if(matchFlag){
       //complete array
    }
}

希望这有帮助!

答案 3 :(得分:0)

您也可以使用Arrays.equals

String array1[] = {"a","b","c","d","e","f"};
String array2[][] = {{"a","b","c","d"}, {"d","e","f","g"}};

for (int i = 0; i < array2.length; i++) {
    if(java.util.Arrays.equals(array1, array2[i]) {
        ...
    }
}