May 11, 2024

Collections framework: ArrayList, HashMap, HashSet

Collections framework: ArrayList, HashMap, HashSet, etc.

The Java Collections framework provides a set of classes and interfaces to store and manipulate groups of objects. The commonly used collections are:

ArrayList

An ArrayList is a resizable array implementation in Java. It dynamically grows and shrinks as elements are added or removed.

List names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

HashMap

A HashMap is a key-value pair data structure. It allows fast retrieval of values based on keys and does not allow duplicate keys.

Map ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 35);
ages.put("Charlie", 40);

HashSet

A HashSet is an implementation of the Set interface. It stores unique elements and does not maintain any order.

Set uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Charlie");

LinkedList

A LinkedList is a doubly linked list implementation in Java. It provides efficient insertion and deletion operations.

TreeMap

A TreeMap is a sorted map implementation in Java. It stores key-value pairs in sorted order based on the natural ordering of keys or a custom comparator.

TreeSet

A TreeSet is a sorted set implementation in Java. It stores unique elements in sorted order based on the natural ordering of elements or a custom comparator.

FAQ (interview questions and answers)

  1. What is the purpose of ArrayList?
    To store a dynamic list of elements
    To store key-value pairs
    To maintain unique elements
  2. How does HashMap store data?
    As key-value pairs
    In a sequential order
    As a single value
  3. What is the main advantage of using HashSet?
    Maintaining order of elements
    Ensuring uniqueness of elements
    Storing key-value pairs
  4. Can ArrayList contain duplicate elements?
    Yes
    No
    Sometimes
  5. How do you access elements in a HashMap?
    Using an index
    Using keys
    Using values

Your Total Score: 0 out of 5

Remember to just comment if you have any doubts or queries.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.