Getting back primitive array after insertion into an ArrayList of primitive arrays in Java

后端 未结 4 1414
日久生厌
日久生厌 2020-12-18 17:42
List x = new ArrayList();
x.add(new double[]={1,2,3,4,54,6});  

elements 1,2,3,4,54,6 are added to x



        
4条回答
  •  盖世英雄少女心
    2020-12-18 18:24

    This is because the List is being made up of double[] instead of double.

    Because a double[] is an array, you have to specify the position from that array as well. Like so:

    x.get(0)[0]
    

    If you want to be able to just use x.get(), your List must be made up of double primitives. Then you can add the array of doubles to the List using a separate method (I don't know of one that is built in):

    List addArray(List o, double[] a) {
      for(Double d : a)
        o.add(d);
    
      return o;
    }
    

    Hopefully that makes sense. I like using short variable names to make the logic more clear. As long as you know what the variables are, you should be fine.

提交回复
热议问题