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

Explain the importance of finalize() method.

569


What are the data types supported by java? What is autoboxing and unboxing?

549


What is role of void keyword in declaring functions?

578


What is the maximum size of hashmap in java?

536


What is the benefit of inner / nested classes ?

527






Explain jdk, jre and jvm?

567


How do you check if a string is lexicographically in java?

503


Mention a package that is used for linked list class in java.

529


What is oop in java?

526


What data type is true or false?

577


What is a 16 bit word?

567


What is java console application?

558


What are new features introduced with java 8 ?

552


What value is a variable of the string type automatically initialized?

613


What happens when heap memory is full?

528