Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java Generic Types

Tags:

java

generics

Consider this Generics Code:

interface Collection<E>  {  
   public void add (E x);  
   public Iterator<E> iterator(); 
} 

And this one:

public class MyClass<V> {
    V v;
    setSomeValue(V val) {
       v=val;
    }

    V getSomeValue() {
        return v;
    }
 }

My Question: Do those letters in angular brackets: <V> and <E> have specific meaning. Can i use any English Alphabet. i.e can they be <A> or <Q>?

like image 484
Jasper Avatar asked Jan 16 '23 10:01

Jasper


1 Answers

They do have to be valid Java identifiers (not necessarily just single letters as pointed out in the comment,) technically you can use any identifier that you like and your code will compile and run fine (if there are no other errors of course!)

It's good to stick to convention though - this tends to be single capital letters. Some common ones are E, T, K and V, standing for element, type, key and value respectively - your use case may well fit into one of those categories, in which case I'd use those letters. In the case of the above example, the Collection class uses E because it contains elements.

like image 109
Michael Berry Avatar answered Jan 25 '23 01:01

Michael Berry