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 any type we want:box<integer> Integerbox = new box<integer> (); box<double> Doublebox = new box<double> (); box<string> Stringbox = new box<string> ();
Generic method 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;}}
We can call the generic method as follows: Pair<integer, string> p1 = new pair<> (1, "Apple"); Pair<integer, string> p2 = new Pair<> (2, "pear"); Boolean same = Util.<integer, String>compare (P1, p2);
Boundary character
Now we're going to implement a feature that looks at the number of a generic array that is larger than a particular element, and we can do this:
Public interface Comparable<t> {public int compareTo (T o);} public static <t extends comparable<t>> int Countgreaterthan (t[] anarray, T elem) { int count = 0; for (T E:anarray) if (E.compareto (Elem) > 0) ++count; return count;}
Java Generics Introduction