有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何修复ArrayList类型的类型不匹配错误?可能的多维数组?

所以我一直在尝试在我的课堂上编写静态的方法来实践我所学到的东西。我对泛型类型和ArrayList的理解仍然是空的,这就是为什么我在这里问这个问题,因为故障排除非常可怕(我目前正在阅读Java Core第9版第一版第6章)

该方法应该接受任意数量的双数组(创建一个多维数组),并检查每个数组是否包含少于或多于三个双元素,然后处理这些数组等等。。。如果数组包含少于两个双精度元素,则显示错误并退出。如果超过3个,则创建该数组的Arraylist并删除超过的任何元素

当我试图在多维数组“DDs”的for-each循环中创建数组“d”的ArrayList时,我的问题出现了。我采纳了this问题中的每一条建议,但没有一条有效,我尝试了其他网站中的一些其他建议,但同样没有起作用。下面是我的代码片段

public static final void Calcs(double[]... DDs)
{
    for(double[] d : DDs)
    {
        if(d.length < 3)
        {
            System.out.println("Variable Error 1 :: Array Distributed exceeds 3 types");
            System.exit(0);
        }else if(d.length > 3)
        {
            ArrayList<Double> tmp = new ArrayList<>(Arrays.asList(d));
            //Type mismatch: cannot convert from ArrayList<double[]> to ArrayList<Double>
        }
    }

}

我的假设是数组d被另一个数组包围。但我不确定,而是问有这样做的人:

我认为x应该是什么样子:

d = [x]

我认为它可能是这样的:

d = [[x]]

有什么解决问题的办法吗?我对泛型类型非常陌生,这个错误告诉我的不多。非常感谢您的反馈


共 (2) 个答案

  1. # 1 楼答案

    这是汇编的,但我不确定这是否是您所寻求的:

    public static final void Calcs ( double[]... DDs ) {
        for ( double[] d : DDs ) {
            if ( d.length < 3 ) {
                System.out.println("Less than 3");
                System.exit(0);
            }
            ArrayList<double[]> tmp = new ArrayList<>(Arrays.asList(d));
        }
    }
    

    也许是这样,那么:

    public static final void Calcs ( double[]... DDs ) {
        for (double[] d : DDs ) {
            if (d.length < 3) {
                System.out.println("Less than 3");
                System.exit(0);
            }
            ArrayList<Double> tmp = new ArrayList<>(d.length);
            for ( double od : d ) tmp.add(od);
        }
    }
    
  2. # 2 楼答案

    你有两个选择。您可以将2D数组(因为varargs实际上是一个数组)视为Listof double[],或Listof List<Double>

    第一种方法是

    List<double[]> list = new ArrayList<>(Arrays.asList(DDs)); //Arrays.asList() returns a fixed size list so we'll put it into a flexible list
    

    第二种方法是

    List<List<Double>> list = new ArrayList<>();
    for (double[] doubles : DDs) {
        List<Double> listDoubles = new ArrayList<>(); //Cannot use Arrays.asList() because that will return List<double[]> with a single element
        for (double innerDouble : doubles) {
            listDoubles.add(innerDouble);
        }
        list.add(listDoubles);
    }