Difference hashmap and arraylist

Asked

Viewed 2,157 times

4

Could someone explain to me the difference between HashMapand ArrayList?

1 answer

6


ArrayList

is a set of elements of a defined type. It is an ordered structure of data, that is, the values can be accessed by its indices.

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 your 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 single key attached to it. The elements in a HashMap must be accessed by your keys.

Example:

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

That 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"
  • Grateful for the explanation, I was able to understand perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.