Java FAQ's Generics

Source: Internet
Author: User

1, first look at the following code: two ways to compare: >>> do not use generics: can add different types of data, easy to lead to security issues
  
  1. @Test
  2. public void test01() {
  3. List list = new ArrayList();
  4. list.add("张三丰");
  5. list.add(100);
  6. System.out.println(list);
  7. }
>>> when using generics: Add code security, only the data type of the generic class
  
  1. @Test
  2. public void test02() {
  3. List<String> list = new ArrayList<>();
  4. list.add("张三丰");
  5. list . add ) Span class= "lit" >100 //error, unable to add an int element to the collection of string generics, compile-time directly cannot pass
  6. System.out.println(list);
  7. }
Note: When subclasses inherit a generic class, you must explicitly define the specific type of the generic class, and the static method cannot use generics, and the generic method can be static

Java FAQ's Generics

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.