Welcome, Guest. Please login or register.
Did you miss your activation email?
Pages: [1]   Go Down
  Print  
Author Topic: Generics  (Read 856 times)
0 Members and 1 Guest are viewing this topic.
Arkie
Javaforums.net Admin
Senior Member
*

Reputation: 16
Developer @ Javaforums.net
Offline Offline
Posts: 2593
Referrals: 13

WWW Awards
« on: March 30, 2009, 06:01:33 AM »

Quote
When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

Here is a simple example taken from the existing Collections tutorial:

Code
GeSHi (java):
  1.    // Removes 4-letter words from c. Elements must be strings
  2.    static void expurgate(Collection c) {
  3.        for (Iterator i = c.iterator(); i.hasNext(); )
  4.          if (((String) i.next()).length() == 4)
  5.            i.remove();
  6.    }
Created by GeSHI 1.0.7.20

Here is the same example modified to use generics:

Code
GeSHi (java):
  1.    // Removes the 4-letter words from c
  2.    static void expurgate(Collection<String> c) {
  3.        for (Iterator<String> i = c.iterator(); i.hasNext(); )
  4.          if (i.next().length() == 4)
  5.            i.remove();
  6.    }
  7.  
Created by GeSHI 1.0.7.20

Generic implements:
Code
GeSHi (java):
  1. public interface MyInterface {}
  2. public class MyClass<T extends MyInterface> {
  3.   //etc, using T as normal
  4. }
Created by GeSHI 1.0.7.20


More info:
http://java.sun.com/j2se/...de/language/generics.html
Logged

Java and .NET developer

To students: It doesn't matter how hard you've studied; the material won't be on the exam anyway.

Fan of http://www.retardedweblogger.com
Oh man, too much stuff to do in so little time.

http://img222.imageshack....707/arkietomatoesmall.jpg
Blizzcon 2k9 Grubby and Cassandra Ng engaged ! <3
Triple D, eerste Denken Dan Doen
Pages: [1]   Go Up
  Print  
 
Jump to:  

Your Ad Here