jump to navigation

Generics August 12, 2005

Posted by Coolguy in J2SE.
trackback
  • Generics allow you to abstract over types.
  • E:g
    List myIntList = new LinkedList(); // 1
    myIntList.add(new Integer(0)); // 2
    Integer x = (Integer) myIntList.iterator().next(); // 3
  • The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast is essential.
  • The compiler can only guarantee that an Object will be returned by the iterator. To ensure the assignment to a variable of type Integer is type safe, the cast is required.
  • Version of the program fragment given above using generics:
    List myIntList = new LinkedList(); // 1
    myIntList.add(new Integer(0)); //2
    Integer x = myIntList.iterator().next(); // 3
  • It specifies that this is not just an arbitrary List, but a List of Integer, written List.
  • The compiler can now check the type correctness of the program at compile-time. When we say that myIntList is declared with type List, this tells us something about the variable myIntList, which
    holds true wherever and whenever it is used, and the compiler will guarantee it.
  • In contrast, the cast tells us something the programmer thinks is true at a single point in the code.
Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: