Java _ generic boundary that you don't know

Source: Internet
Author: User

Java generic boundary: At runtime, the generic is erased and the type is the original type.

1. Type loss in
Import java. util. ArrayList; public class TypeTest {public static void main (String [] args) {// type String in the generic type, Integer in the Class
  C1 = new ArrayList
  
   
(). GetClass (); Class
   C2 = new ArrayList
   
    
(). GetClass (); System. out. println (c1 = c2); // true }}
   
  
//outputtrue
2. Example of complex points: Forced type conversion is still required after the application is generic.
Import java. lang. reflect. Array; import java. util. Arrays; @ SuppressWarnings ("hiding") public class ArrayMaker
  
   
{Private Class
   
    
Kind; public ArrayMaker (Class
    
     
Kind) {this. kind = kind;} @ SuppressWarnings ("unchecked") T [] create (int size) {// here Array. the newInstance () method returns the Object and must be transformed. This indicates that the expected generic type does not play any role. return (T []) Array. newInstance (kind, size) ;}@ SuppressWarnings ("unchecked") T [] create (T t, int size) throws InstantiationException, IllegalAccessException {// Array here. the newInstance () method returns the Object and must be transformed. This indicates that the expected generic type does not play any role T [] ts = (T []) Array. newInstance (kind, size); // Note: The T [] type can still be set to Tfor (int I = 0; I
     
      
StrsMaker = new ArrayMaker
      
       
(String. class); String [] strsArray = StrsMaker. create (10); String [] strsArray2 = StrsMaker. create ("AA", 10); System. out. println (Arrays. toString (strsArray); System. out. println (Arrays. toString (strsArray2 ));}}
      
     
    
   
  
//output[null, null, null, null, null, null, null, null, null, null][AA, AA, AA, AA, AA, AA, AA, AA, AA, AA]

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.