In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the design method of Java generics". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the design method of Java generics".
Introduction
Generics is a very important knowledge point in Java, and it is widely used in Java collection class framework. In this article, we will look at the design of Java generics from scratch, which will involve wildcard handling and annoying type erasure.
Generic basic generic class
Let's first define a simple Box class:
Public class Box {private String object;public void set (String object) {this.object = object;} public String get () {return object;}}
This is the most common practice, one of the disadvantages is that Box can only load elements of String type, in the future, if we need to load other types of elements such as Integer, we have to rewrite another Box, the code can not be reused, using generics can solve this problem very well.
Public class Box {/ / T stands for "Type" public void set (T t) {this.t = t;} public T get () {return t;}}
So our Box class can be reused, and we can replace T with any type we want:
Box integerBox = new Box (); Box doubleBox = new Box (); Box stringBox = new Box (); generic method
After looking at generic classes, let's take a look at generic methods. Declaring a generic method is simple, as long as you precede the return type with a similar form:
Public class Util {public static boolean compare (Pair p1, Pair p2) {return p1.getKey (). Equals (p2.getKey ()) & & p1.getValue (). Equals (p2.getValue ());} public class Pair {private K key;private V value;public Pair (K key, V value) {this.key = key;this.value = value;} public void setKey (K key) {this.key = key;} public void setValue (V value) {this.value = value } public K getKey () {return key;} public V getValue () {return value;}}
We can call generic methods like this:
Pair p1 = new Pair (1, "apple"); Pair p2 = new Pair (2, "pear"); boolean same = Util.compare (p1, p2)
Or use type inference in Java1.7/1.8 to let Java automatically derive the corresponding type parameters:
Pair p1 = new Pair (1, "apple"); Pair p2 = new Pair (2, "pear"); boolean same = Util.compare (p1, p2); boundary character
Now we are going to implement the function of finding the number of elements greater than a particular element in a generic array, which we can do as follows:
Public static int countGreaterThan (T [] anArray, T elem) {int count = 0 for (T e: anArray) if (e > elem) / / compiler error++count;return count;}
But this is obviously wrong, because in addition to short, int, double, long, float, byte, char and other primitive types, other classes may not be able to use the operator >, so the compiler reports an error, so how to solve this problem? The answer is to use boundary characters.
Public interface Comparable {public int compareTo (To);}
Making a declaration similar to the following is tantamount to telling the compiler that the type parameter T represents a class that implements the Comparable interface, which is tantamount to telling the compiler that they have at least implemented the compareTo method.
Public static int countGreaterThan (T [] anArray, T elem) {int count = 0 for (T e: anArray) if (e.compareTo (elem) > 0) + + count;return count;} wildcard
Before we understand wildcards, we must first clarify a concept or borrow the Box class we defined above, suppose we add a method like this:
Public void boxTest (Box n) {/ *... * /}
So what types of parameters are allowed for Box n now? Can we pass in Box or Box? The answer is no. Although Integer and Double are subclasses of Number, there is no relationship between Box or Box and Box in generics. This is very important, so let's deepen our understanding through a complete example.
First, let's define a few simple classes, which we will use below:
Class Fruit {} class Apple extends Fruit {} class Orange extends Fruit {}
In the following example, we create a generic class Reader, and then in F1 () when we try Fruit f = fruitReader.readExact (apples); the compiler reports an error because there is no relationship between List and List.
Public class GenericReading {static List apples = Arrays.asList (new Apple ()); static List fruit = Arrays.asList (new Fruit ()); static class Reader {T readExact (List list) {return list.get (0);}} static void F1 () {Reader fruitReader = new Reader (); / / Errors: List cannot be applied to List.// Fruit f = fruitReader.readExact (apples);} public static void main (String [] args) {F1 ();}}
But according to our usual thinking habits, there must be a connection between Apple and Fruit, but the compiler can't recognize it, so how do you solve this problem in generic code? We can solve this problem by using wildcards:
Static class CovariantReader {T readCovariant (List)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.