Magnum
Magnum

Reputation: 83

Inserting in List of lists using Array.asList in java

I am coding in java and i have three arrays also i have a List of lists.

int[] recovery=bl.generateRecovery();
    int[] periods = bl.generatePeriods(recovery);
    int[] deadlines =  bl.generateDeadlines(periods);

    List<List<Integer>>temp=new ArrayList<List<Integer>>();

Now i want to add the arrays as lists in the list.

I tried using:

temp.add(Arrays.asList(recovery));

But it failed. Can someone tell me how to do it ??

Upvotes: 3

Views: 426

Answers (3)

Dabiuteef
Dabiuteef

Reputation: 475

Arrays.asList(recovery) will give you a List<int[]> object, not List<Integer>. Try using Integer[] recovery instead.

Edit: You might want to have your methods like generateRecovery etc. to return List<Integer> instead of int[]. Arrays are not flexible and it is usually better to use List.

Upvotes: 3

You are trying to fusion two different types (int[] and ArrayList<>). They are not the same, you have to unify your arrays to one of the types.

    int[] recovery= {1,2,3};

    List<int[]>temp=new ArrayList<>();

    temp.add(recovery);

    System.out.println(temp.get(0)[1]);

This code prints a 2.

Upvotes: 0

Naman
Naman

Reputation: 31958

You can make use of Arrays.stream on int[] boxed and collected as List as:

temp.add(Arrays.stream(recovery).boxed().collect(Collectors.toList()));

Upvotes: 3

Related Questions