Data structure and collections: Modern, generics version. : Generic Collection « Generics « Java






Data structure and collections: Modern, generics version.

Data structure and collections: Modern, generics version.
   
/*
Java 2, v5.0 (Tiger) New Features
by Herbert Schildt
ISBN: 0072258543
Publisher: McGraw-Hill/Osborne, 2004
*/
 
import java.util.*; 
 
public class NewStyle {  
  public static void main(String args[]) { 
 
    // Now, list holds references of type String. 
    ArrayList<String> list = new ArrayList<String>(); 
 
    list.add("one"); 
    list.add("two"); 
    list.add("three"); 
    list.add("four"); 
 
    // Notice that Iterator is also generic. 
    Iterator<String> itr = list.iterator(); 
 
    // The following statement will now cause a compile-time eror. 
//    Iterator<Integer> itr = list.iterator(); // Error! 
 
    while(itr.hasNext()) { 
      String str = itr.next(); // no cast needed 
 
      // Now, the following line is a compile-time, 
      // rather than runtime, error. 
//    Integer i = itr.next(); // this won't compile 
 
      System.out.println(str + " is " + str.length() + " chars long."); 
    } 
  }  
}
           
         
    
    
  








Related examples in the same category

1.Creating a Type-Specific List
2.A list declared to hold objects of a type T can also hold objects that extend from T.
3.A value retrieved from a type-specific list does not need to be casted
4.Generic ArrayListGeneric ArrayList
5.Generic Data Structure
6.Unchecked Example
7.Generic StackGeneric Stack
8.Enum and GenericEnum and Generic
9.Generic HashMapGeneric HashMap
10.Foreach and generic data structureForeach and generic data structure
11.Pre generics example that uses a collection.Pre generics example that uses a collection.
12.Java generic: Generics and arrays.
13.Collections and Data structure: the generic wayCollections and Data structure: the generic way
14.The GenStack Class
15.Create a typesafe copy of a raw set.
16.Create a typesafe copy of a raw list.
17.Create a typesafe copy of a raw map.
18.Create a typesafe filter of an unchecked iterator.
19.Create a typesafe view over an underlying raw set.
20.Create a typesafe view over an underlying raw map.
21.Create a typesafe filter of an unchecked enumeration.
22.Circular Object Buffer
23.A collection that do not hold stored elements in memory, but serialize it into a file
24.Generic Triple structure
25.Generic Pair
26.A generic bag of properties used to store properties that apply to a specific target.
27.Pool container