How to sort collection of object?

Is Collection<?> the same as Collection<? extends Object>?

  • Here is a phrasing that is easier on the eyes...   Which of the following is Collection<?> shorthand for: Collection Collection<? extends Object> Collection<? super Object> None of the above - it is an entirely unique concept And what is the rationale for the design decision?

  • Answer:

    Collection is not type safe. Elements of any type can be added to the collection, and when removed they can be casted to any type without a warning. This code compiles without any warnings (just a note about using unchecked operations). Collection c = new ArrayList<Object>(); c.add(new Object()); Boolean b = (Boolean)c.iterator().next(); Collection<?> is a collection of objects of unknown type. You can't put anything into such a collection other than null. You can cast whatever you get out of it without a warning. This fails to compile since the add call is illegal. Collection<?> c = new ArrayList<Object>(); c.add(new Object()); Boolean b = (Boolean)c.iterator().next(); Collection<? extends Object> is almost exactly the same as Collection<?>. See http://stackoverflow.com/questions/2016017/unbounded-wildcards-in-java/2017530#2017530 for a discussion on the differences. Collection<? super Object> can only store Objects (just like Collection<Object>). This compiles cleanly and fails at runtime due to the bad cast. Collection<? super Object> c = new ArrayList<Object>(); c.add(new Object()); Boolean b = (Boolean)c.iterator().next();

Tim Wilson at Quora Visit the source

Was this solution helpful to you?

Other answers

It is shorthand for generic collections

Abhay Lolekar

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.