java – Hashmap and arraylist difference

Question:

Could someone explain to me the difference between HashMap and ArrayList ?

Answer:

ArrayList

is a set of elements of a defined type. It is an ordered data structure, meaning values ​​can be accessed by their indexes.

Example:

ArrayList<string> lista = new ArrayList<>();
lista.add("Stack");
lista.add("Overflow");

That would be something like

Index | Elemento
  0   | "Stack"
  1   | "Overflow"

These elements can be accessed by their index.

String str1 = lista.get(0); //str1 receberá "Stack"

HashMap

It is a set of key-value pairs, for each element (value) saved in a HashMap there must be a unique key attached to it. Elements in a HashMap must be accessed by their keys.

Example:

HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Stack");
hashMap.put(5, "Overflow");

This would be something like:

Key | Value
 1  | "Stack"
 5  | "Overflow"

These elements can be accessed by the key

String str = map.get(5); //str receberá "Overflow"
Scroll to Top