Is there a way to create a list of primitive int or any primitives in java like following?
List myList = new ArrayList();
Is there a way to convert an Integer[] array to an int[] array?
This gross omission from the Java core libraries seems to come up on pretty much every project I ever work on. And as convenient as the Trove library might be, I am unable to parse the precise requirements to meet LPGL for an Android app that statically links an LGPL library (preamble says ok, body does not seem to say the same). And it's just plain inconvenient to go rip-and-stripping Apache sources to get these classes. There has to be a better way.
In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object
they cannot be used as generic type arguments for a parametrized type.
Instead use the Integer
class which is a wrapper for int
:
List<Integer> list = new ArrayList<Integer>();
If your using Java 7 you can simplify this declaration using the diamond operator:
List<Integer> list = new ArrayList<>();
With autoboxing in Java the primitive type int
will become an Integer
when necessary.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
So the following is valid:
int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);
System.out.println(list.get(0)); //prints 1
Collections use generics which support either reference types or wilcards. You can however use an Integer
wrapper
List<Integer> list = new ArrayList<>();
Java Collection should be collections of Object only.
List<Integer> integerList = new ArrayList<Integer>();
more from JAVA wrapper classes here!
U can directly save and get int to/from integerList as,
integerList.add(intValue);
int intValue = integerList.get(i)
When you use Java for Android development, it is recommended to use SparseIntArray
to prevent autoboxing between int
and Integer
.
You can finde more information to SparseIntArray
in the Android Developers documentation and a good explanation for autoboxing on Android enter link description here
Try using the ArrayIntList from the apache framework. It works exactly like an arraylist, except it can hold primitive int.
More details here -
https://commons.apache.org/dormant/commons-primitives/apidocs/org/apache/commons/collections/primitives/ArrayIntList.html