×

Differences between Set and List in Java

Set in Java:

The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates are prohibited. The mathematical set is produced using the set interface. The set interface uses the collection interface's methods to prevent the insertion of duplicate elements. There are two interfaces that improve the set implementation: SortedSet and NavigableSet.

Syntax:

Set<DataType/Wrapper class> variableName = new Set< > ();

Set Methods:

All the methods from the Collection interface are included in the Set interface. This is because the Collection interface is the super-interface of the Set collection.

MethodDescription
add ()Adds the desired element to the set using the add () method.
addAll()  Adds every component of the supplied collection to the set using the addAll () method.
Iterator ()  provides a return value that can be used to access the set's elements successively.  
remove ()  Removes the requested element from the set using remove ().  
removeAll ()  eliminates every element from the set that is also present in another set that is supplied.  
retainAll ()  keeps all set elements that are also present in another set that is given.  
Clear ()eliminates every element from the set.
Size ()yields the set's length (the number of entries).  
toArray ()provides an array with each element of the set.
contains ()If the set contains the specified element, the function contains () returns true.  

Set Operations:

Consider two sets (say set c and set d),

We can carry out fundamental set operations like Union, Intersection, and subset using the Java Set interface.

Using c.addAll (d), we can find the Union of two sets, c and d. Using x, we can find the Intersection of two sets, c and d.

Using d.containsAll (c), we can determine whether c is a subset of d. (c).

Union of Sets:

UnionSet.java

import java.util.*;
import java.io.*;


class UnionSet {
    public static void main (String [] args) {
        HashSet <Integer> eNums = new HashSet<> ();
        eNums.add (2);
        eNums.add (4);
        System.out.println ("HashSet1: " + eNums);


        HashSet <Integer> nums = new HashSet<>();
        nums.add (1);
        nums.add (3);
        System.out.println ("HashSet2: " + nums);


        //Union of the given sets
        nums.addAll (eNums);
        System.out.println ("Union is: " + nums);
    }
}

Output:

Differences between Set and List in Java

The Intersection of sets:

import java.io.*;
import java.util.*;
import java.util.HashSet;


class IntersectSet {
    public static void main (String[] args) {
        HashSet <Integer> pNums = new HashSet<>();
        pNums.add (2);
        pNums.add (3);
        System.out.println ("HashSet1: " + pNums);


        HashSet <Integer> eNums = new HashSet<> ();
        eNums.add (2);
        eNums.add (4);
        System.out.println ("HashSet2: " + eNums);


        //Intersection of two sets
        eNums.retainAll (pNums);
        System.out.println ("Intersection is: " + eNums);
    }
}
Differences between Set and List in Java

HashSet in Java:

A collection with hash table storage is made using the Java HashSet class. It implements the Set interface and derives from the AbstractSet class.

The following are the key features of the Java HashSet class:

  • HashSet uses the hashing technique to store the components.
  • HashSet only has distinct components.
  • HashSet accepts a null value.
  • The HashSet class lacks synchronization.

The insertion order is not maintained by HashSet. The hashcodes of the elements are used to insert them in this place.

The optimum method for search operations is HashSet.

HashSet's load factor is 0.75, and its initial default capacity is 16.

HashSet Program:

HashingSet.java

import java.io.*;
import java.util.*;
import java.lang.*;




class Solution {
    public int findDuplicate (int [] nums) {
       HashSet <Integer> p = new HashSet<> ();
       // creation of Hashset 
        int rep = 0;
        // entering numbers into the hash set if a number is with its first frequency 
        for (int i = 0; i < nums.length; i++)
        { 
            if (p.contains (nums [i]))
            {
                rep = nums [i];
                break;
               // if a number is already found in the hash set
               // then it breaks from the loop and returns the duplicate element 
            }
            p.add (nums [i]);
        }
        return rep;
    }
}


class HashingSet
{
public static void main ( String args [])
{
Scanner scan = new Scanner (System.in);
System.out.println ("enter the value of n");
int n = scan.nextInt ();
System.out.println ("enter the array elements");
int [] arr = new int [n];
for (int I = 0; i < n; i++)
{
arr [i] = scan.nextInt ();
}
Solution obj =new Solution ();
            System.out.println ("The duplicate element is " +obj.findDuplicate  (arr));
}
}

Output:

Differences between Set and List in Java

List in Java:

Java's list feature makes it possible to keep an organized collection. It includes index-based techniques for adding, updating, deleting, and searching components. Duplicate elements are also possible. The List can also contain null elements.

The Collection interface is inherited by the List interface, which may be found in Java. util package. It is the interface's ListIterator factory. We can iterate the List both forward and backwards using the ListIterator. The ArrayList, LinkedList, Stack, and Vector classes are the implementation classes for the List interface. In Java programming, the ArrayList and LinkedList are frequently used. Since Java 5, the Vector class has been deprecated.

Syntax:

List<Object> list = new ArrayList<Object> ();

The List is an interface. Hence objects of the type list cannot be made. To build an object, we always require a class that implements this List. Additionally, since Generics were added in Java 1.5, it is now possible to limit the kinds of objects that can be placed in a List. The List is a user-defined "interface" that is implemented by the ArrayList class, which is pre-defined in the Java.util package, just as a number of other user-defined "interfaces" by user-defined "classes".

Array List Program in Java:

ArrayListDemo.java

import java.io.*;
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList<String> a=new ArrayList<String>();
System.out.println("the size of the ArrayList is " +a.size());
System.out.println("the objects of ArrayList are " +a);
a.add("APRICOT");
a.add("MANGO");
a.add("GRAPES");
System.out.println("the size of the ArrayList is " +a.size());
System.out.println("the objects of ArrayList are " +a);
System.out.println("\n1-using for-each loop");
for(String i:a)
{
System.out.println(i);
}//i
a.add("GUAVA");
a.add("BANANA");
System.out.println("the size of the ArrayList is " +a.size());
System.out.println("the objects of ArrayList are " +a);
System.out.println("\n2-using iterator");
Iterator it=a.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
a.add("APPLE");
a.add("ORANGE");
System.out.println("the size of the ArrayList is " +a.size());
System.out.println("the objects of ArrayList are " +a);
System.out.println("\n3.1-using ListIterator in forward direction");
ListIterator lit=a.listIterator();
while(lit.hasNext())
{
System.out.println(lit.next());
}//while


System.out.println("\n3.2-using ListIterator in backward direction");
while(lit.hasPrevious())
{
System.out.println(lit.previous());
}//while
System.out.println("the size of the ArrayList is " +a.size());
System.out.println("the objects of ArrayList are " +a);
a.remove(3);
a.remove("APPLE");
System.out.println("the size of the ArrayList is " +a.size());
System.out.println("the objects of ArrayList are " +a);
}//main
}//ArrayListDemo

Output:

Differences between Set and List in Java

Differences between set and list:

The List and the Set are both parts of the Collection framework in Java. Set and List interfaces are used to store the collection of objects as a single entity. In addition to these similarities, both interfaces have the following differences:

S.noSETLIST
1.Here, we cannot add identical or duplicate elements using the set implementation.Here, we can add identical or duplicate elements using the list implementation.
2.Order of inserting elements is not maintained by set interface.List interface maintains the insertion order of elements.
3.Insertion of null values is not allowed, at least one null value is allowed by set interface.Insertion of null values are allowed in lists.
4.Set implementation classes include HashSet, TreeSet and LinkedHashSet.List implementation classes include LinkedList and ArrayList.
5.Set interface does not provide a get method, we are unable to locate an element from the Set based on the index ().The get () method allows us to retrieve an element from a list at a specific index.
6.When we want to create a collection of unique elements, we use it.It is utilized when we frequently need to use the index to access the elements.
7.When we need to iterate the Set elements, we use the iterator.The elements of the List are iterated using the listiterator () method of the List interface.

Related Topics

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.