Introduction
Generics are a very important point of knowledge in Java, and generics are widely used in the Java Collection Class framework. In this article we will look at the Java generics design from scratch, which will involve wildcard processing and the distressing type erasure.
Generic Foundation
Generic class
Let's start by defining 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, the downside of this is that box can now only load elements of string type, in the future if we need to load other types of elements such as Integer, but also have to rewrite a box, the code is not reused, the use of generics can be a good solution to the problem.
Public class box<t> {
//T stands for "Type"
Private T T;
Public void set (T t) { this. t = t;}
Public T get () { return t;}
}
So that our Box class can be reused, we can replace T with whatever type we want:
box<integer> Integerbox = new box<integer> ();
box<double> Doublebox = new box<double> ();
box<string> Stringbox = new box<string> ();
Generic methods
After reading the generic class, let's look at the generic method. Declaring a generic method is simple, as long as the return type is preceded by a similar <k, the form of v> is OK:
Public class Util {
Public static <k, v> boolean compare (Pair<k, v> p1, pair<k, v> p2) {
return P1.getkey (). Equals (P2.getkey ()) &&
P1.getvalue (). Equals (P2.getvalue ());
}
}
Public class Pair<k, v> {
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;}
}
"The content display is limited, can add the group to download, the group file will update the study material regularly, as well as practiced hand small case"
"Java Technology 08 Group" Group No. 156643771
Is it hard to learn the design of Java generics from scratch?