简体   繁体   English

Java新手:<>和()之间的区别?

[英]Java newbie: Difference between <> and ()?

I'm learning Java and had a question about the difference between <> and (), such as when defining a class? 我正在学习Java,并且对<>和()之间的区别有疑问,例如在定义类时? 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. 谢谢。

Angle brackets < > are used to indicate generic types. 尖括号< >用于指示通用类型。 For example, a list that contains Strings is type List<String> . 例如,包含字符串的列表的类型为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. 泛型是一个中间主题,如果您是初学者,那么它可能会有些混乱,而无需先了解其他Java和编程基础知识。

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: 因此,如果我想要一个存储LongString类型的键-值对的CounterMap ,可以这样声明和初始化:

CounterMap<Long, String> myCounterMap = new CounterMap<Long, String>();

Starting with Java 7, you can use something called the 'diamond' and simplify it to this: 从Java 7开始,您可以使用称为“钻石”的东西并将其简化为:

CounterMap<Long, String> myCounterMap = new CounterMap<>();

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. 我对这些条款的想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM