1.Why we are unable to add primitives as generic type
Allowed
List<Integer> arrAges = new ArrayList<Integer>();
Not allowed
List<int> arrAges = new ArrayList<int>();
This is to maintain backwards compatibility with previous JVM runtimes in the sense it could be referred by parent class instance Object. Generics in Java are encountered at compile time The compiler converts from generic type to right type as shown in the example below
List<ClassA> list = new ArrayList<ClassA>(); list.add(new ClassA()); ClassA a = list.get(0);
will be turned in to
List list = new ArrayList(); list.Add(new ClassA()); ClassA a = (ClassA)list.get(0);
So anything that is used as generics has to be convert able to Object (in this example get(0) returns an Object), and the primitive types aren’t. So they can’t be used in generics.
2.How to have a Ordered Collections
- keep the insertion order: LinkedHashSet and CopyOnWriteArraySet (thread-safe)
- keep the items sorted within the set: TreeSet, EnumSet (specific to enums) and ConcurrentSkipListSet (thread-safe)