Difference between HashMap and ArrayList in Java?

后端 未结 5 656
北荒
北荒 2020-12-02 10:40

In Java, ArrayList and HashMap are used as collections. But I couldn\'t understand in which situations we should use ArrayList and whi

5条回答
  •  一整个雨季
    2020-12-02 11:25

    Not really a Java specific question. It seems you need a "primer" on data structures. Try googling "What data structure should you use"

    Try this link http://www.devx.com/tips/Tip/14639

    From the link :

    Following are some tips for matching the most commonly used data structures with particular needs.

    1. When to use a Hashtable?

    A hashtable, or similar data structures, are good candidates if the stored data is to be accessed in the form of key-value pairs. For instance, if you were fetching the name of an employee, the result can be returned in the form of a hashtable as a (name, value) pair. However, if you were to return names of multiple employees, returning a hashtable directly would not be a good idea. Remember that the keys have to be unique or your previous value(s) will get overwritten.

    1. When to use a List or Vector?

    This is a good option when you desire sequential or even random access. Also, if data size is unknown initially, and/or is going to grow dynamically, it would be appropriate to use a List or Vector. For instance, to store the results of a JDBC ResultSet, you can use the java.util.LinkedList. Whereas, if you are looking for a resizable array, use the java.util.ArrayList class.

    1. When to use Arrays?

    Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.

    4.Combinations

    Sometimes, it may be best to use a combination of the above approaches. For example, you could use a list of hashtables to suit a particular need.

    1. Set Classes

    And from JDK 1.2 onwards, you also have set classes like java.util.TreeSet, which is useful for sorted sets that do not have duplicates. One of the best things about these classes is they all abide by certain interface so that you don't really have to worry about the specifics. For e.g., take a look at the following code.

      // ...
      List list = new ArrayList();
      list.add(
    

提交回复
热议问题