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

how to split string in java?

647


Can we create more than one object singleton class?

575


Is java same as core java?

584


What is the difference between and ?

505


What is hashmap in java?

562






What do you mean by Hash Map and Hash Table?

596


What is diamond operator in java?

495


Is Constructor possible in abstract class in java ?

586


When a thread is executing a synchronized method , then is it possible for the same thread to access other synchronized methods of an object ?

605


Why do we use regex?

555


Why we used break and continue statement in java?

556


how to open and edit XML file in Weblogic???

1546


Name container classes in java programming?

591


What are decalarations?

635


Is stringwriter thread safe?

552