Sobes.tech
Middle+

Tell me about Java collections, which ones you've worked with, and which are suitable for different tasks.

sobes.tech AI

Answer from AI

In Java, there are several main collections I have worked with:

  • List (ArrayList, LinkedList) — an ordered set of elements. ArrayList is suitable for quick access by index, LinkedList for frequent insertions/deletions in the middle.
  • Set (HashSet, TreeSet) — a collection of unique elements. HashSet provides fast search, TreeSet stores elements in sorted order.
  • Map (HashMap, TreeMap, LinkedHashMap) — stores key-value pairs. HashMap offers quick access without order, TreeMap is sorted by key, LinkedHashMap preserves insertion order.

The choice of collection depends on the task:

  • For storing unique elements without order — HashSet.
  • For an ordered list with quick access — ArrayList.
  • For a map with fast key-based search — HashMap.
  • For sorted data — TreeSet or TreeMap.

Example of using HashMap:

Map<String, Integer> wordCount = new HashMap<>();
wordCount.put("apple", 3);
wordCount.put("banana", 2);
int count = wordCount.getOrDefault("apple", 0);