I want to know: What is a collection in Java?
Usually an instance of java.util.Collection (although java.util.Map is officially also a part of the collections framework)
Although the Collection interface can be implemented directly, usually client code will use an implementation of one of the sub interfaces: Set, List, Queue / Deque
Here is some sample code (on the left side you will usually see an interface and on the right side an implementation class).
Sets don't store duplicates, all of their elements are unique:
final Set<String> basicSet = new HashSet<String>();
basicSet.add("One");
basicSet.add("Two");
basicSet.add("One");
basicSet.add("Three");
System.out.println(basicSet.toString());
// Output: [Three, One, Two]
// (seemingly random order, no duplicates)
SortedSets are a special case of sets that store elements in a specified order:
final SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("One");
sortedSet.add("Two");
sortedSet.add("One");
sortedSet.add("Three");
System.out.println(sortedSet.toString());
// Output: [One, Three, Two]
// (natural order, no duplicates)
Lists let you store a value multiple times and access or modify insertion order:
final List<String> strings = new ArrayList<String>();
strings.add("Two");
strings.add("Three");
strings.add(0, "One"); // add item to beginning
strings.add(3, "One"); // add item at position 3 (zero-based)
strings.add("Three");
strings.add(strings.size() - 1, "Two"); // add item at last-but-one position
System.out.println(strings);
// Output: [One, Two, Three, One, Two, Three]
There is also a practical shorthand for defining a list:
List<String> strings = Arrays.asList("One", "Two", "Three");
// this returns a different kind of list but you usually don't need to know that
etc.
To get a better understanding, read The Collections Trail from the Sun Java Tutorial (online), or Java Generics and Collections by Maurice Naftalin and Philip Wadler
I think this question is best answered in a non-programming sense.
Say you have 5 balls, and you want to move them around easily. You get a bag and place the 5 balls inside of it. The bag acts as a container. You can now move this bag around, and so quite easily the 5 balls move with it.
Simply put, your holding zero or more objects, inside another object for easy retrieval.
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