Are Java generators primarily a way to enforce a static type on collection items?

private ArrayList<String> colors = new ArrayList<String>();

Looking at the example above, it seems that the main motive of generics is to force the use of a type in a collection. Thus, instead of having an array of "Objects", which must be attributed to String at the discretion of the programmer, I use the type "String" in the collection in ArrayList. This is new to me, but I just want to check if I understand it correctly. Is this interpretation correct?

+5
source share
8 answers

, . ArrayList . , - , ArrayList .

- . , JVM , , String. : .

+1

, .

( ) , .

, , , generics/collections, .

+8

, . , , .

+2

. - .

+1

, - Java. .

Generics:

List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next();  // 3

Generics

List<Integer> myIntList = new LinkedList<Integer>(); // 1'
myIntList.add(new Integer(0)); // 2'
Integer x = myIntList.iterator().next(); // 3'

, . autoboxing.

0

Collections.

http://java.sun.com/javase/6/docs/api/java/util/Collections.html#checkedCollection(java.util.Collection,%20java.lang.Class)

. checkedSet, checkedList, checkedSortedSet, checkedMap, checkedSortedMap

0

, . Generics , , , i.e. ArrayList.

, , , , , JVM .

, Generics Java, -. ArrayList<String> ArrayList . , - . , .

0

, type, , , .

, - Java. , Java- -.

, , , . , . , . , 80 . , .

0

All Articles