Java generic knowledge points: Generic classes, generic interfaces, and generic methods

Source: Internet
Author: User

There are many reasons for the emergence of generics, and one of the most noticeable reasons is to create container classes.

Generic class

The container class should be one of the most reusable class libraries. Let's take a look at how a container class is defined without a generic type:

PublicClass Container {Private String key;Private Stringvalue; public container (string k, string v) {key = k; value = V; } public String getkey () {return key ; } public void setKey (String key) { Span class= "Hljs-keyword" >this.key = key; } public String getvalue () {return Span class= "Hljs-keyword" >value; } public void setValue (String value) {this. Value = value;}            

The container class holds a pair of Key-value key-value pairs, but the type is dead, saying that if I want to create a key-value pair that is String-integer type, the current container cannot be done and must be customized. So this obviously reusability is very low.

Of course, I can use object instead of string, and we can only do that before Java SE5, because object is a base class of all types, so it can be transformed directly. But this flexibility is not enough, because the type is still specified, but this time the specified type level is higher, is it possible not to specify the type? Is it possible to know what the specific type is at run time?

As a result, generics are present.

PublicClass Container<k, v> {Private K key;Private Vvalue; public container (k K, v V) {key = K; value = V;} public K getkey () {return key;} Span class= "Hljs-keyword" >public void setkey (K key) {this.key = key; } public V getvalue () {return value; } public void setValue (V value) {this. Value = value;}            

At compile time, it is impossible to know what type K and V are, but only when the runtime actually constructs and allocates memory based on the type. If you want to learn Java can come to this group, the first is 532, the middle is 259, the last is 952, there is a large number of learning materials can be downloaded. You can look at the current container class for different types of support:

PublicClass Main {PublicStaticvoidmain (string[] args) {container<string, string> c1 = new Container<string, string> ( "Findingsea"); container<string, integer> c2 = new container<string, Integer> (" age ", 24); Container<double, double> c3 = new container<double, Double> (1.1, 2.2); System. out.println (C1.getkey () +  ":" + c1.getvalue ()); System. out.println (C2.getkey () +  ":" + c2.getvalue ()); System. out.println (C3.getkey () +   

Output:

name : findingseaage : 241.1 : 2.2

Generic interface

In a generic interface, the generator is a good understanding, see the following builder interface definition:

public interface Generator<T> {    public T next();}

Then define a generator class to implement this interface:

public class FruitGenerator implements Generator<String> { private String[] fruits = new String[]{"Apple", "Banana", "Pear"}; @Override public String next() { Random rand = new Random(); return fruits[rand.nextInt(3)]; }}

Call:

public class Main {    public static void main(String[] args) { FruitGenerator generator = new FruitGenerator(); System.out.println(generator.next()); System.out.println(generator.next()); System.out.println(generator.next()); System.out.println(generator.next()); }}

Output:

BananaBananaPearBanana

Generic methods

A basic principle is that whenever you can do it, you should try to use a generic method. That is, if the generic method can be used instead of generalizing the entire class, then the generic method should be limited. Here's a simple definition of a generic method:

public  Class Main {public static <T> void out (T t) {System. Out.println (t); } public static void main (string[] args) {out (" Findingsea "); out (123); out (11.11); out (true);}        

You can see that the parameters of the method are thoroughly generalized, the process involves the compiler's type deduction and automatic packaging, but also said that the original needs our own type of judgment and processing, now the compiler to help us do. This greatly increases the flexibility of programming by not having to think about which types of parameters to handle later in the process of defining the method.

Let's look at an example of a generic method and a mutable parameter:

public class Main {    public static <T> void out(T... args) { for (T t : args) { System.out.println(t); } } public static void main(String[] args) { out("findingsea", 123, 11.11, true); }}

The output is the same as the previous piece of code, and you can see that generics can be perfectly combined with variable parameters.

Above, the end of the generic section.

Java generic knowledge points: Generic classes, generic interfaces, and generic methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.