0

So I am trying to convert an (primitive) int array to a List,

            for(int i=0;i<limit;i++) {
                arr[i]=sc.nextInt();
            }
            List list=Arrays.asList(arr);
            System.out.print(list);

Doing this so prints values like this for example, [[I@59a6e353] . There is an option to add <Integer> before variable list but since the array is primitive int, it could not. Is there any solution for this? Adding <int[]> before variable list isn't an option as I need to call a bounded wildcard method.

13
  • don't print the list, print the content of the list. Lists don't have an implementation for toString, so your result is to be expected Commented May 17, 2022 at 6:55
  • Use System.out.print(Arrays.toString(list)) Commented May 17, 2022 at 6:56
  • @Stultuske printing the contents of the list gives the same result too. Commented May 17, 2022 at 6:57
  • @Rakkun in that case, how did you try to print the content? Commented May 17, 2022 at 6:59
  • 1
    if you already have an int[] array: List<Integer> list = IntStream.of(array).boxed().toList() - BTW it is recommended not to use raw types! JLS 4.8: "The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of generics into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types." Commented May 17, 2022 at 7:22

2 Answers 2

1

Arrays.asList(arr) does not creates a List<Integer> but a List<int[]> with a single element (your arr). You have to declare your variable as Integer[] arr if you have to use 'Arrays.asList'.

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

Comments

0

The signature of method Arrays.asList is the following one:

public static <T> List<T> asList(T... a);

You can see that it needs an array of generics T in input.

Therefore you can pass an array of Integer and it works. Example:

List<Integer> list= Arrays.asList(new Integer[] {1,2,3,4});
System.out.print(list);

Output:

[1, 2, 3, 4]

If you pass int[] you can have just a List<int[]> because int is a primitive type and it cannot be used as generic. Example:

List<int[]> list= Arrays.asList(new int[] {1,2,3,4});
System.out.print(list);

Output:

[[I@6b1274d2]

I suggest you to read the answer in this question.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.