简体   繁体   中英

How to understand this piece of generics in Java?

This is the sample code from Hadoop's online tutorial ( https://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.html )

public class WordCount {
    public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
    // Something here
    }
}

In the square brackets, there are <LongWritable, Text, Text, IntWritable> and the twice appearance of Text confuses me.

How do we tell which Text it refers to in the actual code since there are two of them with the same name? eg when we use private Text word = new Text();

A similar code in the same piece is public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> .

In order to know which type refers to what you need to take a look at the documentation/implementation of Mapper itself, which you can find here . The generics are called K1 , V1 , K2 and V2 internally and are used throughout the class on various occasions. So whenever something takes K1 as an argument (or returns K1 for that matter), it is referring to the first type you've "plugged" in. It basically (putting inheritance and advanced topics like that aside) is just a simple form of substitution.

By the way: Every (good) IDE should help you out with these matters and infer the correct types you are dealing with automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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