简体   繁体   English

Java类定义:“<>”是什么意思?

[英]Java class definition: what does “<>” mean?

Here is the class definition in java code: 这是java代码中的类定义:

public class WordCount {

 public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        StringTokenizer tokenizer = new StringTokenizer(line);
        while (tokenizer.hasMoreTokens()) {
            word.set(tokenizer.nextToken());
            context.write(word, one);
        }
    }
 } 

So what does this mean? 那么这是什么意思?

public static class Map extends Mapper<LongWritable, Text, Text, IntWritable>

Why we need a "<>" here? 为什么我们需要“<>”?

This is called "generics". 这被称为“泛型”。 It allows you to add type parameters. 它允许您添加类型参数。

In this particular case, it means that Map is a Mapper for tuples of (LongWritable,Text,Text,IntWritable). 在这种特殊情况下,它意味着Map是(LongWritable,Text,Text,IntWritable)元组的Mapper

A simpler example: suppose you have a Set. 一个更简单的例子:假设你有一个Set。 It could be a Set of integers, a set of strings, of MyClass instances.... this is where you use generics. 它可以是MyClass实例的一组整数,一组字符串....这是您使用泛型的地方。
By declaring that a variable is of type Set<Integer> , you specify that it is a set of Integers. 通过声明变量的类型为Set<Integer> ,可以指定它是一组整数。 If you'd just declare it as a Set, you would have to check that it only contained Integers yourself. 如果您只是将其声明为Set,则必须检查它是否仅包含整数。 By adding the type parameter <Integer> , the compiler can now do the type-checking. 通过添加类型参数<Integer> ,编译器现在可以进行类型检查。

Generics are defined here in the Java Language Specification. 泛型的定义在这里的Java语言规范。

Take a look at the declaration of your Mapper class. 看一下Mapper类的声明。 It is possibly something like that class Mapper<E, T, T, K> which declares 3 different generic types . 它可能类似于class Mapper<E, T, T, K> ,它声明了3种不同的泛型类型

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

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