What is Generic in java? Where can we write Generic ( class or method or objects or etc...)? with simple example?
Thanks, Bose.

Answer Posted / inder_gwl

The feature of Generics in Java allows Applications to
create classes and objects that can operate on any defined
types. Programmers can now make use of the Generics feature
for a much better code. There is no need for un-necessary
casting when dealing with Objects in a Collection.
Example without using generics
// 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<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}

Is This Answer Correct ?    32 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is factor r?

715


What is the use of :: in java?

760


What is difference between classpath and path variables in java?

832


How does linkedlist work in java?

685


String and stringbuffer both represent string objects. Can we compare string and stringbuffer in java?

734


What do you understand by an io stream?

781


What is jee6?

726


Is nullpointerexception checked or unchecked?

751


How does system arraycopy work in java?

818


How do you define a variable?

708


Explain the Propertie sof class?

801


What is are packages?

756


How many bytes are a float?

692


What is difference between float and double?

685


Can we have multiple public classes in a java source file?

761