2

I have a 2D Double array that is expanding and I am not sure of its final size therefore I want to convert it to a 2d arraylist but not sure how to do this I tried to define the array list first and use addAll(Array) method but it doesn't work. Any suggestion?

I just wrote this code I think it will work fine but I am looking for more efficient way

public class trial {    

 public static void main(String[] arg){

    double[][] Solutions_to_arrange={{1,5,2,8,4,70,50,80},{3,7,4,2,6,60,30,70},{8,1,6,4,2,10,40,60}};
    ArrayList<ArrayList<Double>> Solutions_to_arrange_A=new ArrayList<ArrayList<Double>>();
    for(int i=0;i<Solutions_to_arrange.length;i++){
        Solutions_to_arrange_A.add(new ArrayList<Double>());
        for(int j=0;j<Solutions_to_arrange[0].length;j++){
            Solutions_to_arrange_A.get(i).add(Solutions_to_arrange[i][j]);
        }
    }

    }
}

Also I have question on putting the statement

Solutions_to_arrange_A.add(new ArrayList<Double>());

Should I put it within the loop or its sufficient to call it just once outside the loop

5
  • 4
    Post your code and the errors you got please. Commented Feb 15, 2015 at 1:27
  • 1
    Is it expanding in both dimensions? Do you want an ArrayList<ArrayList<Double>>, or an ArrayList<Double[]>, or something else? Commented Feb 15, 2015 at 1:35
  • ArrayList<ArrayList<Double>> Commented Feb 15, 2015 at 1:37
  • Your code with a double loop works (I tried it). Unfortunately, since you've defined your array as double[][] and not Double[][], there's really no way to do any better, that I know of. If you make it Double[][], you'll have to put a .0 after every integer, since Java doesn't like converting an unboxed int to a boxed Double automatically. But if you do both of these, you can write code with a single loop using arrays.asList. But this only works in one dimension, so you'd still need one loop. Commented Feb 15, 2015 at 1:50
  • (or you can put D after every integer) Commented Feb 15, 2015 at 1:55

1 Answer 1

4

try it:

    Double[][] matriz = {{1d,5d,2d,8d,4d,70d,50d,80d},{3d,7d,4d,2d,6d,60d,30d,70d},{8d,1d,6d,4d,2d,10d,40d,60d}};

    List<List> result = new ArrayList<>();
    for(Double[] array : matriz){
        result.add( Arrays.asList(array) );
    }

If we use primitive types in "Arrays.asList" we will get a list with one primitive array as its unique item. With object type it will works fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.