Java Generics (i): Getting Started, principles, using

Source: Internet
Author: User

As far back as the JDK version 1.4, there was no concept of generics at that time. The code for Java programmers writing collection classes was similar to the following:

List list = new ArrayList();list.add("www.cnblogs.com");list.add(23);String name = (String)list.get(0);Integer number = (Integer)list.get(1);

By declaring a collection in code, we can put a variety of data into the collection, and cast it in a forced type when it is taken out.

But in fact, such code is a hidden danger, because it may be a short time we will forget the end of the list we have stored in the end of the number is a String, the first number is an Integer. This will cause the following scenario:

List list = new ArrayList();list.add("www.cnblogs.com");list.add(23);String name = (String)list.get(0);String number = (String)list.get(1); //ClassCastException

The above code will have a forced type conversion exception at run time. This is because when we deposit it, the second one is an Integer type, but when it is taken out it is cast to the String type.

The birth of a generic type

In order to make the Java language more secure, Sun has reduced the occurrence of runtime exceptions. The concept of generics was then introduced after JDK 1.5.

So after JDK 1.5, if we use collections to write code, we can use the following form:

List<String> list = new ArrayList();list.add("www.cnblogs.com");list.add("www.cnblogs.com/chanshuyi");String cnBlogs = list.get(0);String myWebSite = list.get(1); 

generics are parameterized types that determine specific parameters at compile time. In the above example, this specific type is String. you can see that we specify the string type when we create the list collection, which means we can only store string types of data in the list collection. When we specify generics, we eliminate the need to force type conversions after we remove the data, which reduces the risk of forcing type conversions.

Above we have two very simple examples of why there are generics, and the simplest use of generics. Let's look at the nature of generics in a common example in an interview.

The nature of generics
ArrayList<String> a = new ArrayList<String>();ArrayList<Integer> b = new ArrayList<Integer>();Class c1 = a.getClass();Class c2 = b.getClass();System.out.println(c1 == c2); 

Before you continue looking down, think about what the output of this problem is.

Is it true or false?

The result of the output of this problem is true. For both ArrayList and ArrayList, their Class types are always arraylist.class.

What exactly is the String and Integer specified when they are declared?

The answer is in the class compile time.

When a JVM makes a class compilation, it performs a generic check, and if a collection is declared as a String type, it will judge the data when it accesses the collection, thus avoiding the need to deposit or remove the wrong data.

That is, generics exist only in the compilation phase, not in the run phase. in the compiled class file, there is no concept of generics.

We're just talking about how generics are used in collections, but in fact generics are not just collections, but classes, methods, MAP interfaces, and so on.

Generics are also widely used in the following scenarios: generic classes, generic methods, generic collections.

Generic class

Generic classes generally use the letter T as a generic flag.

class GenericClass<T> {    private T object; public T getObject() { return object; } public void setObject(T object) { this.object = object; }}

Use:

public static void main(String[] args) {    GenericClass<Integer> integerGenericClass = new GenericClass<>(100); integerGenericClass.showType(); GenericClass<String> stringGenericClass = new GenericClass<>("www.cnblogs.com/chanshuyi"); stringGenericClass.showType();}
Generic methods

Generic methods generally use the letter T as a generic flag.

public class GenericMethod {    public static <T> T getObject(Class<T> clz) throws InstantiationException, IllegalAccessException{ T t = clz.newInstance(); return t; }}

Use:

public static void main(String[] args) throws Exception{ GenericMethod genericMethod = getObject(GenericMethod.class); System.out.println("Class:" + genericMethod.getClass().getName());}
Generic collection

In addition to using T as a flag for a generic class, in a class that needs to use a Map, it is common to use K-V two letters to denote the type of Key Value.

public class GenericMap<K, V> { private K key; private V value; public void put(K key, V value) { this.key = key; this.value = value; }}

Use:

public static void main(String[] args) {        GenericMap<Integer, String> team = new GenericMap<>(); team.put(1, "YaoMin"); team.put(2, "Me"); GenericMap<String, Integer> score = new GenericMap<>(); score.put("YaoMin", 88); score.put("Me", 80); }
Summarize

We understand the cause of the emergence of generics through a simple example, and then we understand the nature of generics only at compile time through a common face test, and finally introduce common generic usage scenarios.

In the next article, we'll cover the use of wildcard characters in generics.

Java Generics (i): Getting Started, principles, using

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.