Create a List of primitive int?

后端 未结 10 1851
夕颜
夕颜 2020-11-27 12:43

Is there a way to create a list of primitive int or any primitives in java like following?

List myList = new ArrayList();
相关标签:
10条回答
  • 2020-11-27 12:51

    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.

    0 讨论(0)
  • 2020-11-27 12:55

    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
    
    0 讨论(0)
  • 2020-11-27 12:55

    Collections use generics which support either reference types or wilcards. You can however use an Integer wrapper

    List<Integer> list = new ArrayList<>();
    
    0 讨论(0)
  • 2020-11-27 12:57

    Java Collection should be collections of Object only.

    List<Integer> integerList = new ArrayList<Integer>();
    

    Integer is wrapper class of primitive data type int.

    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)

    0 讨论(0)
  • 2020-11-27 13:03

    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

    0 讨论(0)
  • 2020-11-27 13:08

    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

    0 讨论(0)
提交回复
热议问题