Generic and collections
4 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   GIRISH_LIMAYE
Posted On:   Thursday, January 14, 2010 05:17 AM

Where in java we can use Generics and Collections at a time.?

Thank you,

Re: Generic and collections

Posted By:   rahul123  
Posted On:   Tuesday, December 17, 2013 08:47 PM

In java generic was introduce in 1.5 v if you are using Generic then you are  automatically using collection

Re: Generic and collections

Posted By:   arnavkumar  
Posted On:   Thursday, November 7, 2013 09:52 PM

Re: Generic and collections
In java generic was introduced in 1.5 in collections. If you are using generic it is obvious to use collections.

Re: Generic and collections

Posted By:   amitg  
Posted On:   Monday, August 6, 2012 08:45 PM

thanks for nice explaination

Re: Generic and collections

Posted By:   Anonymous  
Posted On:   Friday, February 5, 2010 05:30 PM

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:


// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}


Here is the same example modified to use generics:

// Removes the 4-letter words from c
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}


When you see the code , read it as “of Type”; the declaration above reads as “Collection of String c.” The code using generics is clearer and safer. We have eliminated an unsafe cast and a number of extra parentheses. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness.

About | Sitemap | Contact