Java generics: Generic classes, generic interfaces, and generic methods

Source: Internet
Author: User
Tags pear rand

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:

PublicClassContainer {Private String key;private String value;PublicContainer(string k, String v) {key = k; value = V;}public String getKey () {return key;} public void setkey (String key) {this.key = key;} public String getValue () {return value;} public void setvalue (String value) {this.value = value; }} 

ContainerThe class holds a pair of key-value key-value pairs, but the type is dead, and it says that if I want to create a key-value pair that is String-Integer type, this Container is not the current one and must be customized. So this obviously reusability is very low.

Of course, I can use it Object instead String , and we can only do that before Java SE5, because Object it's all types of base classes, so it's a straightforward transformation. 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.

PublicClasscontainer<Kv> {Private K key;private V value;PublicContainer (k K, v V) {key = K; value = V;} public K getKey  () {return key;} 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 K V what the type is, and only when the runtime actually constructs and allocates memory based on the type. You can look at Container the current classes for different types of support situations:

PublicClassMain {PublicStaticvoid main(string[] args) {container<string, string> c1 = new container<string, string> (  "Name", "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 () + ":" + c3.getvalue ());}}          

Output:

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

One basic principle is: whenever you can, you should try to use a generic method. that is, if a 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.

Java generics: 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.