Collections and Data structure: the generic way : Generic Collection « Generics « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Generics » Generic CollectionScreenshots 
Collections and Data structure: the generic way
Collections and Data structure: the generic way
  

/*
License for Java 1.5 'Tiger': A Developer's Notebook
     (O'Reilly) example package

Java 1.5 'Tiger': A Developer's Notebook (O'Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8

You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.util.ArrayList;

import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class GenericsTester {

  public GenericsTester() {
  }

  public void testTypeSafeMaps(PrintStream outthrows IOException {
    Map<Integer, Integer> squares = new HashMap<Integer, Integer>();

    for (int i=0; i<100; i++) {
      squares.put(i, i*i);
    }

    for (int i=0; i<10; i++) {
      int n = i*3;
      out.println("The square of " + n + " is " + squares.get(n));
    }
  }

  public void testTypeSafeLists(PrintStream outthrows IOException {
    List listOfStrings = getListOfStrings();
    for (Iterator i = listOfStrings.iterator(); i.hasNext()) {
      String item = (String)i.next();
 
      // Work with that string
    }

    List<String> onlyStrings = new LinkedList<String>();
    onlyStrings.add("Legal addition");
    /**
     * Uncomment these two lines for an error
    onlyStrings.add(new StringBuilder("Illegal Addition"));
    onlyStrings.add(25);
     */
  }

  public void testTypeSafeIterators(PrintStream outthrows IOException {
    List<String> listOfStrings = new LinkedList<String>();
    listOfStrings.add("Happy");
    listOfStrings.add("Birthday");
    listOfStrings.add("To");
    listOfStrings.add("You");

    for (Iterator<String> i = listOfStrings.iterator(); i.hasNext()) {
      String s = i.next();
      out.println(s);
    }

    printListOfStrings(getListOfStrings(), out);
  }

  private List getList() {
    List list = new LinkedList();
    list.add(3);
    list.add("Blind");
    list.add("Mice");

    return list;
  }

  private List<String> getListOfStrings() {
    List<String> list = new LinkedList<String>();
    list.add("Hello");
    list.add("World");
    list.add("How");
    list.add("Are");
    list.add("You?");

    return list;
  }

  public void testTypeSafeReturnValues(PrintStream outthrows IOException {
    List<String> strings = getListOfStrings();
 
    for (String s : strings) {
      out.println(s);
    }
  }

  private void printListOfStrings(List<String> list, PrintStream out)
    throws IOException {

    for (Iterator<String> i = list.iterator(); i.hasNext()) {
      out.println(i.next());
    }
  }

  public void printList(List<?> list, PrintStream outthrows IOException {
    for (Iterator<?> i = list.iterator(); i.hasNext()) {
      out.println(i.next().toString());
    }
  }

  public static void main(String[] args) {
    GenericsTester tester = new GenericsTester();

    try {
      tester.testTypeSafeLists(System.out);
      tester.testTypeSafeMaps(System.out);
      tester.testTypeSafeIterators(System.out);
      tester.testTypeSafeReturnValues(System.out);

      List<Integer> ints = new LinkedList<Integer>();
      ints.add(1);
      ints.add(2);
      ints.add(3);
      tester.printList(ints, System.out);

      /** Uncomment for an error
      NumberBox<String> illegal = new NumberBox<String>();
       */
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
class NumberBox<N extends Number> extends Box<N> {

  public NumberBox() {
    super();
  }
 
  // Sum everything in the box
  public double sum() {
    double total = 0;
    for (Iterator<N> i = contents.iterator(); i.hasNext()) {
      total = total + i.next().doubleValue();
    }
    return total;
  }  

  public static <A extends Number> double sum(Box<A> box1,
                                              Box<A> box2) {
    double total = 0;
    for (Iterator<A> i = box1.contents.iterator(); i.hasNext()) {
      total = total + i.next().doubleValue();
    }
    for (Iterator<A> i = box2.contents.iterator(); i.hasNext()) {
      total = total + i.next().doubleValue();
    }
    return total;
  }
}

class Box<T> {

  protected List<T> contents;

  public Box() {
    contents = new ArrayList<T>();
  }

  public int getSize() {
    return contents.size();
  }

  public boolean isEmpty() {
    return (contents.size() == 0);
  }

  public void add(T o) {
    contents.add(o);
  }
 
  public T grab() {
    if (!isEmpty()) {
      return contents.remove(0);
    else
      return null;
  }
}
           
         
    
  
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. Data structure and collections: Modern, generics version.Data structure and collections: Modern, generics version.
13. Java generic: Generics and arrays.
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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.