DEV Community

Divya Divya
Divya Divya

Posted on

List and Set in Java

Why do we use List and Set in Java?

Normal Arrays some limitations:

  • Array size is fixed and can not be changed dynamically.
  • There is no built-in control for handling duplicate elements.
  • Managing and manipulating data can be difficult.

So,we use List and Set in the Java collection Framework to manage data easily.

List in Java:

List is an interface in the Java collection Framework.

Features of List:

  • Maintain insertion order.
  • Allows duplicate elements.
  • Supports index-based access.
  • Dynamically resizes as needed.

List implementation classes:

  • ArrayList
  • LinkedList
  • Vector
  • Stack

ArrayList: Stores data using a dynamic array.
ArrayList<String> list = new ArrayList<>();
LinkedList: Stores data using a linked list structure.
LinkedList<String> list = new LinkedList<>();

Example:

Apple
Mango
Apple
Orange
Enter fullscreen mode Exit fullscreen mode

Apple is repeated, so we can use a List.

Set in Java:

Set is an interface in the Java collection Framework.
Features of Set:
Does not allow duplicate elements.
Stores only unique value.
Provides efficient search and insertion operations.
Useful when uniqueness of data is required.

Set implementation classes:

HashSet:Stores unique elements and does not maintain insertion order.
Set<String> set = new HashSet<>();
LinkedHashSet: Stores unique elements and maintains insertion order.
Set<String> set = new LinkedHashSet<>();
TreeSet:Stores unique elements in sorted order.
Set<String> set = new TreeSet<>();

Example:

Apple
Mango
Apple
Orange
Enter fullscreen mode Exit fullscreen mode

Here, "Apple" is added twice.

Apple
Mango
Orange
Enter fullscreen mode Exit fullscreen mode

But, the Set stores it only once because duplicates are not allowed.

Top comments (0)