September 07, 2010, 04:27:43 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  Home Help Media Affiliates Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Generics  (Read 924 times)
0 Members and 1 Guest are viewing this topic.
Arkie
Javaforums.net Admin
Senior Member
*

Reputation: 16
Developer @ Javaforums.net
Offline Offline
Posts: 2620
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
Javaforums.net :: a community about Java software development.
« on: March 30, 2009, 06:01:33 AM »

Your Ad Here
 Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.10 | SMF © 2006-2009, Simple Machines LLC
TinyPortal v0.9.8 © Bloc
Valid XHTML 1.0! Valid CSS!
Page created in 0.211 seconds with 32 queries.

Google visited last this page September 04, 2010, 05:15:40 AM