Java Generics-several usage methods

Source: Internet
Author: User
Tags comparable

Summary:This section describes several usage methods of generics.

Definitions of simple classes and interfaces:

public class Pair<T> {private T first;public Pair(T first) {this.first = first;}public T getFirst() {return first;}}

public interface ICache<K, V> {public V put(K key, V value);public V get(K key);}

PS: type variables are in uppercase and are short. In the Java library, variable e Represents the elements of the Set, and K and v represent the types of table keywords and values respectively. T indicates "any type ".

Generic method:

public class Test {public static <T> T getObj(T a) {return a;}public static void main(String args[]) {String str = getObj("a");Student student = getObj(new Student());}}class Student {}

This is certainly not the case in the example of the actual code, but it represents an obvious advantage of the generic method: t can be of any type ".

Inheritance of type variables:

public class ArrayTest {public static <T extends Comparable> T min(T[] a) {if (a == null || a.length == 0)return null;T smallest = a[0];for (int i = 1; i < a.length; i++) {if (smallest.compareTo(a[i]) > 0) {smallest = a[i];}}return smallest;}}

Here, T must ensure that the compareto method is available. Therefore, use <t extends comparable> to limit T to the comparable interface.

PS: <t extends bounding type> indicates that T should be the word type (subtype) of the binding type, and t and the binding type can be classes or interfaces. I think it can be understood that the keyword extends here is not the extends keyword in inheritance, and it is only a code for the compiler. The designer selects the keyword extends because it is closer to the concept of subclass.

References:

Java core technology volume 1

Thomescai http://blog.csdn.net/thomescai (reprinted please keep)

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.