Reputation: 197
I'm learning Java and had a question about the difference between <> and (), such as when defining a class? For example:
public class CounterMap<K, V> implements java.io.Serializable {
private static final long serialVersionUID = 11111;
MapFactory<V, Double> mf;
Map<K, Counter<V>> counterMap;
protected Counter<V> ensureCounter(K key) {
Counter<V> valueCounter = counterMap.get(key);
if (valueCounter == null) {
valueCounter = new Counter<V>(mf);
counterMap.put(key, valueCounter);
}
return valueCounter;
}
}
Any insight would be appreciated. Thanks.
Upvotes: 0
Views: 121
Reputation: 19682
Somewhat related.
parameter, variable, argument --
void f(Number n) // define a parameter `n` of type `Number`
{
// here, `n` is a variable. (JLS jargon: "parameter variable")
}
f(x); // invoke with argument `x`, which must be a `Number`
type-parameter, type-variable, type-argument --
<N extends Number> f() // type-parameter `N` with bound `Number`
{
// here, `N` is a type-variable.
}
<Integer>f(); // instantiate with type-argument `Integer`, which is a `Number`
my thoughts on these terms.
Upvotes: 0
Reputation: 2410
Angle brackets < >
are used to indicate generic types. For example, a list that contains Strings is type List<String>
. Generics is an intermediate topic which - if you're a beginner - might be a little confusing, without first understanding other Java and programming basics.
Parentheses ( )
are used to invoke and declare methods, and they contain method parameters and arguments.
Your example is using generics to store any type of data in a map without having to be specific about what the type is. So if I wanted a CounterMap
that stored key-value pairs of Long
and String
types, I could declare and initialize it like so:
CounterMap<Long, String> myCounterMap = new CounterMap<Long, String>();
Starting with Java 7, you can use something called the 'diamond' and simplify it to this:
CounterMap<Long, String> myCounterMap = new CounterMap<>();
Upvotes: 2