Can I convert array of integer to List<int> or List<Integer> by Arrays.asList(array)? [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?
Or must I refactor int[] to Integer[] ?

You can't have List<int>
Arrays.asList(array); will return you List with type T of (passed array)
You can have something like
Integer[] a = new Integer[]{1,2,3};
List<Integer> lst = Arrays.asList(a);

You can do this way
Integer[] a ={1,2,4};
List<Integer> intList = Arrays.asList(a);
System.out.println(intList);

Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.
Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:
List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]> list2 = Arrays.asList(new int[]{1,2,3}));
The first collection holds the integer values, the second one the int[] array. No autoboxing here.
So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.

If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:
Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);

EDIT :
From the comment below from develman, java 6 has support to return List<> object for same method
OLD ANSWER :
Arrays.asList(array) returns you a java.util.List object.

Related

Getting a List<Integer> from a resource array

I have a string-array resource with integers.
<string-array name="navChildRatings">
<item>12</item>
<item>12</item>
<item>17</item>
<item>123</item>
<item>8</item>
</string-array>
My goal is to have them into a list of type List<Integer>
As a first step I know they can be assigned into an integer array by:
int[] ratings = Arrays.asList(getResources().getIntArray(R.array.navChildRatings));
I am trying to avoid looping through the array of integers (ints) and having to add one by one to the List of Integers (java.lang.Integer).
Is there a direct way to get the string-array into a List<Integer>?
or, alternatively
Is there a direct way to assign the int[] array to a List<Integer>?
Note: My motivation is purely to have a more elegant code. I know how to do it by looping the array. But, for example, in the case of Strings it works if you assign it directly:
List<String> names = Arrays.asList(getResources().getStringArray(R.array.navChildNames));
Unofortunately this is impossible since asList is not handling boxing (wrapping primitive) and will not create objects automatically.
If you want to keep code elegant and using Java8 you can easily create lambda to do it as one-liner
if you do not use Java8 just create a simple method to convert int[] to List
ArrayList<Integer> getList(int[] a)
{
List<Integer> l = new ArrayList<Integer>();
for(int i : a)
l.add( new Integer(i) );
return l;
}
and then
List<Integer> items = getList(ratings);

Defining an array of List of integers in Java

I have an array. For each element of the array, I want to store multiple integers. I know that in C I can make an array of integer pointers, and use that pointer to make a list.
In Java, I can make an array of object 'A', where A has a list of integers. But why can't I do something like this
List<Integer>[] arr = new ArrayList<Integer>[]();
I get:
Type mismatch: cannot convert from ArrayList to List[]
You typically want to avoid mixing collections and arrays together for this very reason; an array is covariant (that is, Integer[] is-an Object[]), but collections (and generics in general) are invariant (that is, a List<Integer> is not a List<Object>).
You can definitely create a list of lists instead, which will ensure type safety and get you around the issue of creating a generic array:
List<List<Integer>> intNestedList = new ArrayList<>();
As stated in Java's own documentation, you cannot create an array of generics.
If you want to create an array which can hold up to ten List<Integer> you must declare the array that way.
List<Integer>[] arr = new ArrayList[10];
following assignment is valid
List<Integer> intList = new ArrayList<>();
arr[0] = intList;
whereas following will fail with an compilation error
List<String> stringList = new ArrayList<>();
arr[0] = stringList;
the compilation fails with
incompatible types: java.util.List<java.lang.String>
cannot be converted to java.util.List<java.lang.Integer>
An ArrayList is a List, but an ArrayList is not a List[]
If you want an Array of Lists that hold integers, I would suggest:
List<Integer>[] xyz; // still writing code will update in a sec
It turns out you can't create arrays of parameterized types, according to the oracle docs.
Unless you know for sure you want a finite array, I suggest you do something like List<List<Integer>> arr = new ArrayList<List<Integer>>();
If you really want an array of Lists then you'll want to see this Java question about ArrayList<Integer>[] x
Creating an array of List is no different than creating an array of any other object. You can do any of the following:
List[] listsArray = new List[3];
listsArray[0] = new ArrayList();
listsArray[1] = new LinkedList();
listsArray[2] = new ArrayList();
Or:
List[] listsArray = new List[]{new ArrayList(), new LinkedList(), new ArrayList()};
Note that you are limited in what you can do with generics on arrays.
Not a very nice solution but you might try it with a cast. Something like this:
List<Integer>[] arr = (List<Integer>[]) new List[SIZE_OF_YOUR_ARRAY];
You will probably get a warning but it should still work.
As i found, you need an array of arrays.
you can do this, to make your inner arrays:
Integer[] array1 = new Integer[];
Integer[] array2 = new Integer[];
and then put them in another array like this:
Integer[][] arrays = new Integer[][] { array1, array2 };
or
Integer[][] arrays = { array1, array2 };
maybe it's better to do it like this:
List<List<Integer>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("123","456","789"));
after all I recommend you to read this:
How to make an array of arrays in Java
Graph Implementation using Adjacency List depicts the usage of an Array of List.
public class Graph {
int vertex;
LinkedList<Integer> list[];
public Graph(int vertex) {
this.vertex = vertex;
list = new LinkedList[vertex];
for (int i = 0; i <vertex ; i++) {
list[i] = new LinkedList<>();
}
}
}
As you can observe that the constructor of class Graph, is used to define the Array of List.
in the same constructor, Array Of List is initialized too.
Hope It would be Helpful to resolve your problem and requirement !.

java : Understanding Arrays.asList(T...array) method for primitive types

I wrote following code and was surprised to see the output:
Integer a = 211;
int b = 211;
int[] array = {210,211,212};
System.out.println(Arrays.asList(array).contains(a));
System.out.println(Arrays.asList(array).contains(b));
Output:
false
false
I found this question and some other questions linked to it and learned that asList method doesn't Autobox stuffs. I checked the returned type in eclipse javadoc preview:
I couldn't quite understand this return type. int[] is an object and not a primitive so its fine. I'm sure that I'm not getting List<Integer> (something which I expected) but I'm not sure how to use the thing which is being returned. My questions are:
1. How exactly do I expect that list methods will work when I'm expecting an List of Integer and getting a List of int[] ?
2. In case of Strings the return type is List of String and not List of String[]. What sort of implementation differences are there?
3. What good is this method for primitives if things are so uncertain?
There are obviously 3 questions here so lets tackle them one by one:
How exactly do I expect that list methods will work when I'm expecting an List of Integer and getting a List of int[] ?
Well, List methods will work exactly as expected, a List<T> is a list of types T. Here T is an int[] so a List<int[]> will contains arrays as each element:
[{1, 2}, {3, 4}, {1, 6}]
So get(i) will return the ith element. In the case of Arrays.asList the List contains a single element, namely the int[] so:
int[] array = {210,211,212};
List<int[]> list = Arrays.asList(array);
Will be
[{210, 211, 212}]
And so
list.get(0)[0] == 210
In case of Strings the return type is List of String and not List of String[]. What sort of implementation differences are there?
String is an Object, not a primitive type. The difference follows from that.
What good is this method for primitives if things are so uncertain?
Things are not uncertain. This method results in defined and predictable behaviour. It's just not very useful for primitives. This is (yet another) side effect of combining Java's type system with generics.
Note with Java 8 the conversion of an int[] to a List<Integer> is very simple:
List<Integer> list = Arrays.stream(array).
boxed().
collect(toList());
You are not getting a Lit or a List (which can't be), you're getting a List of arrays of integer.
So your list does not contain 211, it contains an array that then contains 211.
The array is not "unrolled" into the list, it is added "as is" to a newly created list.
So :
System.out.println(Arrays.asList(array).contains(array)); // Will return true
System.out.println(Arrays.asList(a).contains(a)); // Will return true
It is because Arrays.asList() is a variadic generic function. Change this,
int[] array = {210,211,212};
to
Integer[] array = { 210, 211, 212 };
And the output will be true and true.
Arrays.asList takes objects as params. Since int[] is an object, you get the List.
If you want a list of integers you should do Arrays.asList(211,212,213).
int[] array = {210,211,212};
Arrays.asList(array)
is equal to
List<int[]> asList = Arrays.asList(array);
Change
int[] array = {210,211,212}; to Integer[] array = {210,211,212}; and it will work.
and its equals to List<Integer> asList = Arrays.asList(array);

List of Arrays in Java

What is the syntax for making a List of arrays in Java?
I have tried the following:
List<int[]> A = new List<int[]>();
and a lot of other things.
I need to be able to reorder the int arrays, but the elements of the int arrays need not to be changed. If this is not possible, why?
Thank you.
Firstly, you can't do new List(); it is an interface.
To make a list of int Arrays, do something like this :
List<int[]> myList = new ArrayList<int[]>();
P.S. As per the comment, package for List is java.util.List and for ArrayList java.util.ArrayList
List<Integer[]> integerList = new ArrayList<Integer[]>();
Use the object instead of the primitive, unless this is before Java 1.5 as it handles the autoboxing automatically.
As far as the sorting goes:
Collections.sort(integerList); //Sort the entire List
and for each array (probably what you want)
for(Integer[] currentArray : integerList)
{
Arrays.sort(currentArray);
}
List is an interface, not a class. You have to choose what kind of list. In most cases an ArrayList is chosen.
List a = new ArrayList();
You've mentioned that you want to store an int array in it, so you can specify the type that a list contains.
List<int[]> a = new ArrayList<int[]>();
While you can have a collection (such as a list) of "int[]", you cannot have a collection of "int". This is because arrays are objects, but an "int" is a primitive.

Why does Arrays.asList on an int[] return a List<int[]>, and not a List<int>?

Consider this code:
int[] tcc = {1,2,3};
ArrayList<Integer> tc = Arrays.asList(tcc);
For the above, Java complains that it cannot convert from List<int[]> to ArrayList<Integer>.
What's wrong with this?
Why is it List<int[]> and not List<int>?
An ArrayList can hold only objects not primitives such as ints, and since int != Integer you can't do what you're trying to do with an array of primitives, simple as that. This will work for an array of Integer though.
This will work:
ArrayList tc = new ArrayList(Arrays.asList(1,2,3));
You could have it as:
List<int[]> tc = Arrays.asList(tcc);
Arrays.asList returns a List, not an ArrayList. And since Arrays.asList is a varargs function, it thinks tcc is one element of a bigger array.
If you want to have just a List of Integers, you'd have to rewrite it as SB mentioned in the comments for Hovercraft Of Eel's answer:
List<Integer> tc = Arrays.asList(1, 2, 3);
Alternatively, if you make tcc an Integer[], you can still use your array as an argument in the following snippet by explicitly asking for a List of Integer, providing a type parameter that agrees with the passed array:
Integer[] tcc = {1,2,3};
List<Integer> tc = Arrays.<Integer>asList(tcc);

Categories

Resources