Welcome to CodeRanch Sarah!
Here's a table of the most important interfaces
you should know, and the classes you should use as their default implementations:
Collection interface | Default implementation to use | When to use the interface |
---|
List | ArrayList | Your elements need to be ordered* or you want to allow duplicate elements. |
Set | LinkedHashSet | You want to disallow duplicate elements. |
SortedSet | TreeSet | You want to keep the elements in your set sorted*. |
Map | LinkedHashMap | Like a Set, but you want to associate each element (key) with another object. |
SortedMap | TreeMap | You want to keep the keys in your map sorted*. |
Queue | ArrayDeque | You want to add elements to the back and retrieve them from the front. |
Deque | ArrayDeque | You want to add and retreive elements to and from either end. |
There are some specialized interfaces like
NavigableSet and
BlockingQueue, but you can read more about them when you become familiar with the basics.
*Ordered means something different than sorted. Ordered means that each element is associated with an index. The list
List.of('D', 'C', 'A', 'B') is ordered, even if it is not sorted, because
'D' is associated with the index
0,
'C' is associated with the index
1, etc.
An important rule is that you never declare variables of a more specific type than you need. Let's say that you just want to keep a collection of objects in memory, and you don't care about their order. You just want to add elements to the collection (possibly duplicates) and iterate through the existing elements. You would then use the
Collection interface, because it does everything you need:
As you can see, while I initialized my collection field with an instance of
ArrayList, I declared it as a
Collection, because that's all I need. Similarly, if you don't need to add any items to a collection and you don't need to check the size of a collection and you only want to iterate through the elements, you can use the
Iterable interface instead of the
Collection interface.
Another important rule: Never use raw types! Collections are generic types, meaning they accept generic type arguments. In the
Collection<Thing> myThings declaration I wrote above,
Thing is the generic type argument. Java allows you to write just
Collection, but that will disable type checking by your compiler, which can be a source of bugs.
The best way to learn is by doing. With these rules in mind, USE collections. Read API documentation of the interfaces while you're using them. Try to use methods you're unfamiliar with to solve problems. Let people review your code, and they might suggest and explain classes and interfaces you're not familiar with yet.