Search code examples
javadata-structures

What is the difference between Lists, ArrayLists, Maps, HashMaps, Collections etc..?


I've been using HashMaps since I started programming again in Java without really understanding these Collections thing.

Honestly I am not really sure if using HashMaps all the way would be best for me or for production code. Up until now it didn't matter to me as long as I was able to get the data I need the way I called them in PHP (yes, I admit whatever negative thing you are thinking right now) where $this_is_array['this_is_a_string_index'] provides so much convenience to recall an array of variables.

So now, I have been working with Java for more than 3 months and came across the interfaces I specified above and wondered, why are there so many of these things (not to mention e.g. Vector, AbstractList {oh well the list goes on…})?

I mean how are they different from each other?

And more importantly, what is the best interface to use in my case?


Solution

  • The API is pretty clear about the differences and/or relations between them:


    Collection

    The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered.

    http://download.oracle.com/javase/6/docs/api/java/util/Collection.html

    List

    An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

    http://download.oracle.com/javase/6/docs/api/java/util/List.html

    Set

    A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

    http://download.oracle.com/javase/6/docs/api/java/util/Set.html

    Map

    An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

    http://download.oracle.com/javase/6/docs/api/java/util/Map.html


    Is there anything in particular you find confusing about the above? If so, please edit your original question. Thanks.