Use of generics in Java collections
Generics provide a lightweight and flexible data operation, and the security of the data is relatively improved.
Generics provide constraints on list elements, such as ArrayList ordered linked lists, which can store any type of element.
A ArrayList object is built here.
New ArrayList ();
You can add elements of any data type to the list list by using the List.add () method, such as:
List.add (1); List.add ("str"); List.add (true); = list.iterator (); while (It.hasnext ()) { System.out.println (It.next ()); }
After the compiler compiles, the output is:
1
Str
True
However, if a generic is used to ArrayList a data constraint, such as ArrayList, it means that only values of type int are allowed to be stored in the ArrayList linked list.
New ArrayList
();
You can add elements of any data type to the list list by using the List.add () method, such as:
List.add (1); // list.add ("str"); This type is string and the compiler will error // List.add (TRUE); This type is a Boolean compiler will error, so comment out = list.iterator (); while (It.hasnext ()) { System.out.println (It.next ()); }
After the compiler compiles, the output is:
1
Visible generics can have a data constraint, which improves the convenience and security of data manipulation.
Use of generics in Java collections