what does generic mean in computer programming? Please provide examples?

John2014-02-20T03:28:25Z

Favorite Answer

dynamic type
public class Program {
public static void main(String[] args) {
Pair<String, Integer> pair = new KeyValuePair<String, Integer>("one", 1);
System.out.printf("K: %s V: %d%n", pair.getKey(), pair.getValue());

Pair<Integer, String> valueString = new KeyValuePair<Integer, String>(1, "one");
System.out.printf("K: %d V: %s%n", valueString.getKey(), valueString.getValue());

}
}

interface Pair<K, V> {
public K getKey();
public V getValue();
}

class KeyValuePair<K, V> implements Pair<K, V> {
private K key;
private V value;

public KeyValuePair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
}

Locoluis2014-02-20T00:32:48Z

List<Integer> is a list of Integer objects.
List<String> is a list of String objects.

But what is a List? It operates generically. It has the same methods regardless of the datatype of the objects in which it operates.

List is probably a bad example, since it's also an interface, which means that its implementation is defined by other classes that implement List. ArrayList is one such implementation.

Don't confuse both concepts. I often do.

You can't do

List x = new ArrayList();

because you don't know which type of data it will hold.

You can do instead:

List<XYZ> x = new ArrayList<XYZ>();

And this will let you hold a list of instances of the class XYZ.

http://en.wikipedia.org/wiki/Generics_in_Java