Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of Collection<?>

Tags:

java

I have been reading Effective Java and I have come across the unbounded Collection type <?>. However, the reading has led me to believe that you can't put any elements, other than null, into an instance of Collection<?>.

So, my question is this: what is the purpose of instantiating a Collection<?> when we can only insert null elements as it seems pointless. I've been trying to figure out this concept, but it just doesn't seems to make much sense. Any help would be much appreciated.

like image 493
blackpanther Avatar asked Aug 20 '13 08:08

blackpanther


People also ask

What is the point of collections?

Collection development has to do with determining the location of copies of materials. There has been a tendency, now diminishing, to use the term to refer only to the selection of materials for acquisition. Adding material to a collection affects where copies may be found, but does not create any new materials.

What is a collection in programming?

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.


1 Answers

Collection<?> allows you to create, among other things, methods that accept any type of Collection as an argument. For instance, if you want a method that returns true if any element in a Collection equals some value, you could do something like this:

public boolean collectionContains(Collection<?> collection, Object toCompareTo) {
    for (Object o : collection) {
        if (toCompareTo.equals(o)) return true;
    }
    return false;
}

This method can be called by any type of Collection:

Set<String> strings = loadStrings();
collectionContains(strings, "pizza");

Collection<Integer> ints = Arrays.toList(1, 2, 3, 4, 5);
collectionContains(ints, 1337);

List<Collection<?>> collections = new ArrayList<>();
collectionContains(collections, ILLEGAL_COLLECTION);
like image 69
BambooleanLogic Avatar answered Oct 23 '22 13:10

BambooleanLogic