Generics in Java5

We use collections daily in our code. How we use it ??

// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) == 4)
When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection.

What is the issue in this code ?

The code 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. Plus the code is not readable.
Here is the same example modified to use generics:
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {

for (Iterator<String> i = c.iterator(); i.hasNext(); )
if ( == 4)

The code using generics is clearer and safer. we have moved part of the specification of the method from a comment to its signature

Categories Uncategorized

3 thoughts on “Generics in Java5

  1. Wonderful goods from you, man. I have take into account your stuff previous to and
    you’re just too excellent. I really like what you’ve acquired right here, really like what you are saying and
    the best way through which you are saying it. You make it enjoyable and you continue to care for to stay it
    sensible. I can’t wait to read far more from you. This is actually a wonderful site.

  2. I love what you guys are up too. Such clever work and reporting!
    Keep up the awesome works guys I’ve you guys to my blogroll.

  3. Howdy! I know this is somewhat off topic but I was wondering which blog platform are you using for this website?
    I’m getting tired of WordPress because I’ve had issues with
    hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close