Instructional Material: Collections
A Collection is an object that stores lists of other objects allowing the group of stored objects to be manipulated in many powerful ways. A Collection may sound like an array or ArrayList and while a Collection is quite different than an array, ArrayList is in fact one implementation of the Collection concept. Java has a large number of specific implementations of the Collection concept you can use. Here are the most commonly used types of Collection:
- set - A list of objects with no duplicates.
- list - A list of objects duplicates allowed. (ArrayList is an implementation of the list general type)
- map - A list of objects with key values (no duplicates).
- queue - A list of objects with features that support sequential processing of the elements.
Within each type, there are a number of actual implementations you can use. Each implementation has specific features or performance aspects that you consider when choosing an implementation to use for your programs. Here is an example:
second string third string first string
new first string first string second string third string second string -------------------- second string third string second string first string new first string
Here we create a List type Collection using the ArrayList implementation and add some elements. Note we added an element using an index (position) and it inserted the element at that location, moving all subsequent elements up. The ArrayList allows us to add a duplicate element. Finally we use the Iterator type ListIterator (a specialized Iterator for List collections) to manually list the elements in forward order and then reverse order. Note that the ListIterator to go in reverse order is created with it's starting position set to the last element in the list by using the list length field to identify the last element's position.
Due to the many types of Collections and the many implementations of the types of Collections, Collections can seem daunting and overly complex. Collections are very powerful tools for manipulating data sets but most cases can be handled by the ArrayList Collection type.
Here is a video on the ArrayList Collection type. Here is a detailed discussion of Collections starting with an introduction and moving through the specific implementations of the various Collection types.
Here is the example code in CodingGround. Add code to the example to use the iterator for myList to locate the element containing "third string" and remove it from the list. Print out the modified myList to confirm the removal.