×

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

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.