Java generic type wildcards versus C

  • 2020-05-12 02:34:30
  • OfStack

Generics of c# do not have type wildcards, because generics of.net are supported by CLR, while JVM of Java does not support generics, just syntax sugar, which is converted to object when the compiler compiles

The type wildcard in java represents the parent of a generic type


public void test(List<Object> c)  
{  
   for(int i = 0;i < c.size();i++)  
   {  
       System.out.println(c.get(i));  
   }  
}  

// create 1 a List<String> object   
List<String> strList = new ArrayList<String>();  
// will strList Call the previous one as a parameter test methods   
test(strList);  

To compile the above program, a compilation error will occur at test(strList), meaning that List cannot be put together < String > As List < Object > This is where you need to use the type wildcard, which is 1 ? No.

The above List < Object > For List < ? > You're ready to compile


public void test(List<?> c)  
{  
   for(int i = 0;i < c.size();i++)  
   {  
       System.out.println(c.get(i));  
   }  
}  

List < String > It can be used as List < ? > Subclass to use, List < ? > Can be used as a parent of any List type,

If you just want to be List < String > The parent class, not List < int > , & # 63; Let me write it like this: List < ? extends String >

In C#, the constraint generics type looks like this


class MyClass<T, U>  
  where T : class  
  where U : struct  
{}  

interface IMyInterface  
{  
}  
  
class Dictionary<TKey, TVal>  
  where TKey : IComparable, IEnumerable  
  where TVal : IMyInterface  
{  
  public void Add(TKey key, TVal val)  
  {  
  }  
}  

Constraint generic wildcard upper bound in Java:


// Show that T The type must be Number Class or its subclasses , And must be implemented java.io.Serializable interface   
Public class Apple<T extends Number & java.io.Serializable>  
{}  

Related articles: