Traps caused by generics

Source: Internet
Author: User
1 package Stu; 2 3 Import Java. util. arraylist; 4 Import Java. util. list; 5 6 public class testlist {7 public static void main (string [] ARGs) {8 list = new arraylist (); 9 10 list. add ("1"); 11 12 list. add (2); // type inconsistent 13 14 list. add ("3q"); 15 16 for (INT I = 0; I <list. size (); I ++) {17 18 system. out. println (list. get (I); 19 20} 21 22 // The first loop output has no problem, and the second loop reports a transformation exception. In other words, the set itself can store objects of 23 24 // different types of elements, but since jdk1.5, there has been a wildcard, so many of us think that a set variable can only store one type of object element. 25 26 // The generic type is designed to better exclude the tedious check caused by type conversion during compilation. In most applications, the elements of the same type are indeed set. 27 28 // with the new cycle strengthened by the generic model, it will force a single type of transformation operation. 29 30 List <string> listnew = List; 31 32 for (string strnew: listnew) {33 34 system. Out. println (strnew); 35 36} 37} 38}

Result:

 

 

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.