Saturday, June 10, 2023

Difference between List and Set in Java Collection? Example

In Java, both List and Set are interfaces that are part of the Java Collections Framework. They are used to store collections of elements, but they have some key differences in terms of their characteristics and usage. 

Definition: 

List: A List is an ordered collection of elements that allows duplicate values. Each element in a List has an index associated with it, which allows for efficient access by index. 

Set: A Set is an unordered collection of unique elements. It does not allow duplicate values, and the elements in a Set have no specific order. 

Duplicate Elements: 

List: List allows duplicate elements. You can add the same element multiple times to a List at different positions. 

Set: Set does not allow duplicate elements. If you try to add the same element multiple times to a Set, only one instance of that element will be present. 

Ordering: 

List: Elements in a List are ordered by their index. The order of elements can be changed, and you can access elements by their index using methods like get(index) and set(index, element). 

Set: Set does not maintain any specific order of elements. The elements are stored in a way that allows for efficient retrieval but does not guarantee any particular order. To iterate over the elements in a Set, you can use an iterator or enhanced for loop. 

Here's an example to illustrate the difference:


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListVsSetExample {
    public static void main(String[] args) {
        // List example
        List list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("orange");
        list.add("apple"); // Duplicate element
        System.out.println("List: " + list); // Output: [apple, banana, orange, apple]

        // Set example
        Set set = new HashSet<>();
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("apple"); // Duplicate element (ignored)
        System.out.println("Set: " + set); // Output: [banana, orange, apple]
    }
}

In the above example, the List allows duplicate elements, so when we print the list, both occurrences of "apple" are present. 

However, the Set does not allow duplicates, so the duplicate "apple" is ignored, and only one instance of it is present in the output.

No comments:

Post a Comment