Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

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

2 Answers

Relevance
  • John
    Lv 7
    7 years ago
    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;

    }

    }

  • 7 years ago

    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

Still have questions? Get your answers by asking now.