Examples of generic wildcard

Generics wildcards:?

Action:
As a generic set of parameters of the method, may receive any type of data
can not be used to create objects

Primary use:

I took some notes, written in a detailed document.

 1 package com.cyl.demo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 public class Demo2 {
 7     public static void main(String[] args) {
 8         ArrayList<Integer> list1 = new ArrayList<>();
 9         list1.add(1);
10         list1.add(2);
11 
12         ArrayList<String> list2=new ArrayList<>();
13         list2.add("hello1");
 14          list2.add ( "of hello2" );
 15  
16          printArraylist (List1);
 . 17          System.out.println ( "different types of dividing line ##### ############# ######## " );
 18 is          printArraylist (List2);
 . 19  
20 is  
21 is      }
 22 is  
23 is      / * 
24          define a can, ArrayList print any data type
 25          in three ways print
 26 is       * / 
27      Private  static  void printArraylist (the ArrayList <?> List) {
 28          System.out.println ( "iterates over ------ ------" );
 29          the iterator IT = <?>list.iterator ();
 30          the while (it.hasNext ()) { // traverse ArrayList, using the while 
31 is              Object it.next O = (); // use to receive any data type Object 
32              System.out.println ( O);
 33 is          }
 34 is          System.out.println ( "traverse the foreach ---- ----" );
 35          for (Object O:
 36               List) {
 37 [              System.out.println (O);
 38 is          }
 39          the System .out.println ( "---- for loop ----" );
 40          for ( int I = 0; I <list.size (); I ++ ) {
41             System.out.println(list.get(i));
42         }
43     }
44 }
View Code

Run effect diagram:

 

 Advanced use (generic settings)

The upper limit is defined:?? E the extends transfer only unknown data type is a subclass of E, E itself or
a lower limit is defined:? Super E unknown data type E can only be passed to the parent class, or E itself?

 

Guess you like

Origin www.cnblogs.com/chenyanlong/p/10972735.html