0

I have a int array with 2 number. I wan to copy this number into array list and print them out. as much as possible refrain from using Integer result[];

  int result[] = {1024,2048};
  List<Integer> res = new ArrayList<Integer>(result);


public class TEA {

    /**
     * @param args
     */
    public static void main(String[] args) {

          int result[] = {1024,2048};
          List<int[]> res = Arrays.asList(result);
          System.out.println(res);


    }

}

output :[[I@3312b1dd]

2 Answers 2

1

If you can't make result into an Integer[] instead of an int[], your options are either to do an explicit for loop:

List<Integer> list = new ArrayList<Integer>();
for (int value : array) {
  list.add(value);
}

...or, if you can use third-party libraries, use Guava's Ints.asList(int[]). That's more or less the entire space of your options.

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

2 Comments

this is to add in new value,so it is not possible to copy existing array without using Integer result[]?
...I'm not sure what you're saying. These are essentially the only options if you want to get an int[] to a List<Integer>, but it's not clear what you mean by "this is to add in new value."
0

Use Arrays.asList() method to do the same.

List<Integer> res = Arrays.asList(result);

This is a list view of the array, you can't add or delete elements.

List<Integer> res = new ArrayList<Integer>(Arrays.asList(result));

Copies all elements from the source array into a new list.

EDITED:

There is no automatic conversion from array of primitive type to array of their wrapper reference types.

int result[] = {1024,2048};
List<Integer> list = new ArrayList<Integer>();
for (int value : result) {
    list.add(value);
}
System.out.println(list);

2 Comments

not working for both...i getting error, i also tired changing integer to int[], it return some rubbish value
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from List<int[]> to List<Integer> at TEA.main(TEA.java:74)

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.