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.
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.
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.
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);
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