Generics in Java

Source: Internet
Author: User

The function of generics is to limit the parameter type and make the code more rigorous. In future use, there will be no errors in parameter calls.

Let's look at the implementation of Java internal class generics.

 1 // IntelliJ API Decompiler stub source generated from a class file 2 // Implementation of methods is not available 3  4 package java.util; 5  6 public interface Map<K, V>   { 7      8     int size(); 9     10     boolean isEmpty();11     12     boolean containsKey(java.lang.Object o);13     14     boolean containsValue(java.lang.Object o);15     16     V get(java.lang.Object o);17     18     V put(K k, V v);19     20     V remove(java.lang.Object o);21     22     void putAll(java.util.Map<? extends K,? extends V> map);23     24     void clear();25     26     java.util.Set<K> keySet();27     28     java.util.Collection<V> values();29     30     java.util.Set<java.util.Map.Entry<K,V>> entrySet();31     32     boolean equals(java.lang.Object o);33     34     int hashCode();35     36     static interface Entry<K, V>   {37         38         K getKey();39         40         V getValue();41         42         V setValue(V v);43         44         boolean equals(java.lang.Object o);45         46         int hashCode();47     }48 }

This is the implementation of the map interface in Java.

Note the methods defined in the map interface,

1 V put(K k, V v);

The Return Value Type and parameter type are both K and V. That is to say, it does not limit a strong type, such as integer or string.

You can set the generic type to integer or string based on your needs to limit future input and parameter types and call to parameter methods.

We usually write this when calling

1 Map<String, String> strMap = new HashMap<String, String>();

Here, when we perform the put operation on strmap, the input type can only be string

The element obtained from strmap is also the most string class.

The types in generics can also support inheritance.

1 class Sort<E extends Comparable<E>> { /** **/ }

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.