Lets say I have the class :
class Box<T>{}
Now what is the difference between :
public myMethod(Box box){};
and
public myMethod(Box<?> box){};
Update:
I'm asking because I want to see the effect on the variable box, Is the variable identical in both cases or not.
Collection<?>(pronounced "collection of unknown"), that is, a collection whose element type matches anything.
I am not sure about your Box class definition so it is hard to describe it from that. But if you use any collection such as List, Map, Set. Then you can define the type of objects it may contain using generics. So if the type is not defined then it means you are allowing the raw types in your colection as mentioned here
Collection c;
But if you want this collection to store only a particular type then you can specify it using generfic. For examlple a collection of String:
Collection<String> c;
But if you want to allow any type of object to be stored then you use collection of unknown, as defined here:
Collection<?> c;
Using generics, allow you to find problems during compile time.
Read more here: http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
Generics have been introduced into Java to help you catch a wide range of bugs in compile-time, instead of just encountering ClassCastException at runtime.
When you use <?> (a wildcard) you are saying to the compiler that you don't know (or don't care about) the generic type. For example: if you just want to count the number of elements of an Iterable<?>, you simply don't care about the types of the elements, so you could create a method with the signature int countElements(Iterable<?> iterable), that would simply retrieve an Iterator<?> from the iterable (note the wildcard type again), and then just call hasNext() and next(), while incrementing a counter.
You could do the same without the <?>, which is what is called a raw type.
You should almost never use raw types. Raw types are allowed since Java tries to be as backwards compatible as possible. If they didn't allow you to use raw types, almost all Java code from versions before 1.5 (when Generics have been introduced) would have to be rewritten; the raw types allows the compiler to compile that code -- although it will issue warnings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With