abalfazl hossein wrote:By using of Wildcards,You can use any type of objects: <?>
But it is said the reason for using generic is type safety.
Actually no. Wildcards doesn't remove type safety. What it does is remove some knowledge of the type -- which in turn allows you to write code that can handle more generic types.
Type safety is still enforced. And it is enforced by restricting what you can do with the wildcard generic. For example, if your code takes a List<?>, it can handle a List of any generic type, but type safety is still enforced, as you won't be able to add anything (but null) to that List -- at least not via the wildcard generic reference..
Or LinkedList. Or the object returned by Arrays.asList. Or any other List implementation. But the generic type does not matter; a List<Object>, List<String>, List<Integer>, List<Moose> - it's all allowed.
Because you cannot assign a List<Integer> object to a List<Object> reference:
If that line did not provide an error you could add an Object to objectList, which means that that Object would be added to intList as well. In other words, you'd get an Object in a List<Integer>. List<?> solves that by not allowing anything to be added (other than null which is assignable to any reference).
One thing to remember is that List<?> is only valid as a reference type. You can't create a List<?>. A variable of List<?> means "I can point to any type of List you want - but it will still have to be a specific type".
So the difference between a List<Object> and a List<?> is that the former can hold any object, whereas the latter can hold any object of a specific (but unknown) type. That's why you can't add anything to a List<?> - the compiler can't tell what's safe.
But it doesn't mean it's not useful, because sometimes all you need is a reference that can hold any list. Look at some of the methods in the Collections class. They are mainly general purpose methods for working with any sort of list you want (sorting, searching etc), and they make heavy use of wildcards.
Because those are the types that Double is compatible with - the interfaces it directly and indirectly implements and the direct and indirect super classes. The Comparable is generic by itself so that too has a few options, but again - things that Double is comparable with.
(Note that the <? super Double> is equivalent to <Double> since Double is final.)