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

后端 未结 4 1402
日久生厌
日久生厌 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<Double> addArray(List<Double> 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.

    0 讨论(0)
  • 2020-12-18 18:25

    If you just want your list to store the doubles instead of arrays of doubles, change what the list is storing

    List<Double> doubleList = new ArrayList<Double>();
    

    Then you can add the array as a list to your array list which will mean the list is storing the values rather than the array. This will give you the behaviour that get(0) will give you 1 rather than the array address

    Double[] doubleArray = {1.0, 2.0, 3.0, 4.0, 54.0, 6.0 };
    doubleList.addAll(Arrays.asList(doubleArray));
    doubleList.get(0); //gives 1.0
    
    0 讨论(0)
  • 2020-12-18 18:25

    The default toString() implementation of any Object (including the double[]) is the return of the Object address. This is what it is printed by your code.

    0 讨论(0)
  • 2020-12-18 18:33

    double[] array is object. So, you get address and entire array is added at index 0.

    You may use Arrays.toString(x.get(0)) to get readable array print.

    toString() for an array is to print [, followed by a character representing the data type of the array's elements, followed by @ then the memory address.

    0 讨论(0)
提交回复
热议问题