There is a method that converts a two-dimensional array into an ArrayList .

 public List<Integer> toList (int[][] array) { List list = new ArrayList(); for (int[] i : array) { list.addAll(Arrays.asList(i)); } return list; } 

Call him.

 public static void main(String[] args) { ConvertList convertList = new ConvertList(); System.out.println("Массив: " + convertList.toList(new int[][]{{1, 2}, {3, 4}})); } 

And what I get in the end: Массив: [[I@1540e19d, [I@677327b6]

Explain, please, what am I doing wrong?

    1 answer 1

    The Arrays.asList(T... a) method takes a parameter of the form T... a , which means an array of objects of type T The mistake is that in your head you mean by type T in this case the type is int , but int is a primitive , and it cannot be a generic. Therefore, T is understood as an object of type int[]

    As a result, in your list 2 elements with the type int[] , it looks like this:

    1: [1,2]

    2: [3,4]

    For correction I suggest 2 ways:

    1. Replace primitive type int with Integer

       System.out.println("Массив: " + toList(new Integer[][]{{1, 2}, {3, 4}}) //........ //........ public List<Integer> toList (Integer[][] array) { List list = new ArrayList(); for (Integer[] i : array) { list.addAll(Arrays.asList(i)); } return list; } 
    2. Expand the internal array by hand

       public List<Integer> toList (int[][] array) { List list = new ArrayList(); for (int[] i : array) { for(int j : i){ list.add(j); } } return list; } 

    Yes, actually, if you declared the List list variable correctly , like List<Integer> list , then your code would not even compile, in your case there is only a warning that you should pay attention to.

    • Thank you very much for the answer) Both the first and second options work, but I need the second option, since the "int [] [] array" was a condition in the problem. - Dmitry Serov