如何在JAVA中将数组名称存储在数组中?

时间:2016-06-17 08:14:31

标签: java arrays function

这是我的问题: -

我有两个字符串数组,其中包含数组名称(整数)作为字符串。 现在我需要将每个整数数组与剩余的数组进行比较。

假设我有阵列

    int[] data;
    data1 = new int[] {10,20,30,40,50,60,71,80,90,91};
    data2 = new int[] {10,20,30,40,50,60,71,80,90,91};
    data3 = new int[] {10,20,30,40,50,60,71,80,90,91};
    data4 = new int[] {10,20,30,40,50,60,71,80,90,91};
    data5 = new int[] {10,20,30,40,50,60,71,80,90,91};

   /*Now divide the above data into two parts like data1 and data2 is in one side and other content is other side and each array will compare with other set of arrays. i.e. array data1 will compare with array data3, data4, data5. and same for data2 array */

    String [] str= new String[2];
    String [] str1= new String[3];

    str[0]="data";  //Name Of the first array.
    str[1]="data2"; //This is also other array name

     str1[0]="data3";
     str1[1]="data4";
     str1[2]="data5";
    //Now I need to call a function passing array name as the parameter.

   for(int i=0;i<str.length();i++)
   {
     for(int j=0;j<str1.length();j++)
      {
        compare(str[i],str1[j]);   //this is error part   


    //and the function definition is 
    public void compare(int[] x1, int[] x2)
    {//compare code
    }

但是得到错误: - 不兼容的类型:String不能转换为int []

1 个答案:

答案 0 :(得分:2)

您正尝试将String传递给接受int[]的方法。 我在这里看到两种方式:

  1. 创建单独的类来存储数组的名称,数组本身并将该类的对象传递给方法compare。
  2. 使用Map<String, Integer[]>存储“名称” - &gt; int[]
  3. import java.util.HashMap;     import java.util.Map;

    public class Main {
    
        public static final String NAME_1 = "data";
        public static final String NAME_2 = "data2";
    
        public static void main(String[] args) {
            Map<String, int[]> data = new HashMap<>();
            data.put(NAME_1, new int[]{10, 20, 30, 40, 50, 60, 71, 80, 90, 91});
            data.put(NAME_2, new int[]{10, 20, 30, 40, 50, 60, 71, 80, 90, 91});
            // etc...
            compare(data.get(NAME_1));
        }
    
        public static void compare(int[] x1) {
            for (int i = 0; i < 10; i++) {
                System.out.println(x1[i]);
            }
        }
    
    }