Java generic type wildcard character and C # contrastive analysis _java

Source: Internet
Author: User

C # 's generics do not have a type wildcard because. NET generics are generics supported by the CLR, and Java JVMs do not support generics, just syntactic sugars, which are converted to object type at compile time

The type wildcard represents the parent class of a generic type in Java

public void Test (list<object> c)  
{for  
   (int i = 0;i < C.size (); i++)  
   {  
       System.out.println (c.get (i));  
   }  
  
Create a List<string> object  
list<string> strlist = new arraylist<string> ();  
Call the previous test method  
test (strlist) by strlist as a parameter;  

Compiling the above program, test (Strlist) will have a compile error, meaning that list<string> can not be treated as a list<object> subclass. This is where the type wildcard is used, and the wildcard character is a number.

The above list<object> replaced by list<?> can be compiled

public void Test (list<?> c)  
{for  
   (int i = 0;i < C.size (); i++)  
   {  
       System.out.println ( i));  
   }  
  

List<string> can be used as a subclass of List<?>, and list<?> can be used as a parent of any List type.

What if you just want to be a list<string> parent, not a list<int>? Write such list<? Extends string>

Constraining the generic type in C # is this

Class Myclass<t, u>  
  where T:class  
  where u:struct  
{}  
Interface IMyInterface  
{  
}  
  
class Dictionary<tkey, tval>  
  where tkey:icomparable, ienumerable< C11/>where tval:imyinterface  
{public  
  void Add (TKey key, Tval val)  
  {  
  }  
}  

constraint generic wildcard upper bound in Java:

Indicates that the T type must be a number class or its subclass and must implement the Java.io.Serializable interface public  
class Apple<t extends number & Java.io.serializable>  
{}  

The above is a small series for everyone to bring Java generic type wildcard and C # Comparative analysis of all the content, I hope that we support cloud Habitat Community ~

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.