java program – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 10 Mar 2024 17:30:22 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg java program – Programmerbay https://programmerbay.com 32 32 Multiple Inheritance in Java With Program Example https://programmerbay.com/multiple-inheritance-in-java-with-program-example/ https://programmerbay.com/multiple-inheritance-in-java-with-program-example/#respond Sat, 03 Feb 2024 16:27:51 +0000 https://programmerbay.com/?p=9046 In object-oriented programming (OOP), inheritance is a feature that allows a class or an interface to inherit attributes and behaviour from another class or interface. The class that is being inherited, is known as the parent class, while the class that inherits is termed as the child class.

In Java, inheritance can be implemented either through classes or interfaces. In the case of class, the parent class provides behavioural implementation (non-abstract method) that its child class acquires and reuses. But in the case of interfaces, the parent interface only supplies behavioural specification (abstract method) and the implementation is provided only when a class implements the interface.

Multiple Inheritance

Multiple Inheritance is a type of inheritance in which a class inherits more than one class. It may increase the complexity of a program as it can introduce deadly diamond or ambiguity problems. Apart from this, one also has to take care of special rules to prevent ambiguities, leading to extra efforts to deal with such cases.

multiple inheritance in Java

Therefore, unlike C++, Java doesn’t support multiple inheritance of implementation. As a result, a class cannot have more than one superclass or parent class. However, it does support this type of inheritance in the case of the interface. A basic construct, named interface, consists only of declaration, not implementation. Hence, an interface can inherit multiple interfaces.

multiple inheritance in java using interfaces

 

Syntax for multiple inheritance in Java :

interface A {
// members
}

interface B {
// members
}

interface C extends A, B{
// members
}

 

Ambiguity Problem or Diamond Problem in Java [Read more in brief : click here]

It is also known as the deadly diamond of death. This problem arises when a class acquires properties from multiple parent classes. For instance, suppose there are two classes, namely Person and Employee and both are having a common functionality getAge().

If a new class tries to inherit Programmer and Person at the same time, then it would automatically get getAge() method from both the parent classes. Further, the class would have two versions of getAge() with different implementations.

As a result, it would create ambiguity problem for the compiler, while identifying which version of getAge() to be selected – Person or Programmer.

This ambiguity or confusion is termed the diamond problem.

Therefore, Java doesn’t support multiple inheritance in classes.

Trying to Implement Multiple inheritance program in Java

As we know, multiple inheritance is not supported in the case of classes. It happens because two classes having the same method and different implementations can create ambiguity.

To check this on a programmatic level, we’ll be trying to implement the inheritance in form of a program.

Program:

class Employee {
    float salary;

// getting age of an employee
    int getAge(){
        return 21;
    }
}

class Person {
    String name;

    // getting age of a person
    int getAge(){
        return 23;
    }
}

// Trying to apply multiple inheritance by extending two class at time
class Programmer extends Employee,Person{

    public static void main(String[] args) {
        Programmer programmer = new Programmer();
        // Trying to get Age of a programmer
        System.out.println("Total salary for you programmer :: "+programmer.getAge());
    }
}

Error:

error: '{' expected
class Programmer extends Employee,Person{
                                 ^

Explanation:

  1. There are two classes named Person and Employee that have a common method getAge() in which each of them has their implementations
  2. When the Programmer class is trying to extend both the classes Person and Employee, a compile time exception is occurred

Multiple inheritance using interface in Java

Java doesn’t provide support for multiple inheritance of implementation ( non-abstract method or concrete class) but in the case of inheritance of interfaces or specifications (abstract methods), Java provides support for it.

It is because an interface can only provide only a declaration of a method, not implementation. As a result, when a class implements multiple interfaces and if a common method is available in those interfaces, it has to provide a single implementation which doesn’t create ambiguity.

An interface can have multiple parent interfaces at the same time. The functionality’s been demonstrated in the below example.

Java program to implement multiple inheritance using interface

Program:

interface Employee {
// getting age of an employee
    int getProgrammerAge();
}

interface Person {

    // getting age of a person
    int getProgrammerAge();
}
// Applying multiple inheritance by extending two interfaces at a time

interface Programmer extends Employee,Person{

    String getProgrammerName();
}

class Program implements Programmer{

    public static void main(String[] args) {
        Program code1 = new Program();
        // Trying to get Age of a programmer
        System.out.println("The code is written by :: "+code1.getProgrammerName()+" and age :: "+code1.getProgrammerAge());
    }

    @Override
    public int getProgrammerAge() {
        return 21;
    }

    // Overriding the method inherited from the interface
    @Override
    public String getProgrammerName() {
        return "Kui";
    }
}

Output:

The code is written by :: Kui and age :: 21

Explanation:

  1. In the above example, there are interfaces named Employee and Person.
  2. Both the interfaces is having abstract method getProgrammerAge(). Another interface Programmer is extending both of them, Employee and Person. And it also has a non-abstract method gerProgrammerName().
  3. As a result, the child interface has the access of getProgrammerAge() of both the parent interfaces.
  4. Now, the Program class has implemented the programmer interface. The class has provided implementation for both the methods gerProgrammerName() and getProgrammerAge().
  5. Since,  getProgrammerAge() was only a declaration, not implementation, it doesn’t matter, if two interfaces has the same method or not, at last they would be limited to declaration. The only part that differentiate them is implementation of the method, which is at the end provided by inheriting class.

The Solution of Diamond Problem

The default method that was introduced in Java 8, is the solution of the diamond problem or ambiguity problem. A default method is an implementation method within an interface. It is not mandatory for implementing classes to override it as its implementation is already provided by the interface.

It allows multiple inheritance to some extent. A default method with the same method name can be present in two or more interfaces. If a class implements them, then it would inherit properties of both.

In the case of default methods, Java defines a set of rules which needs to follow:
1) When a class overrides a default method of the implementing interface, then the class implementation would take the priority.

Example.

interface A {
    default void display() {
        System.out.println("I am a method from interface A");
    }
}

interface B {
    default void display() {
        System.out.println("I am a method from interface B");
    }

}

class C implements A,B{

    @Override
    public void display() {
        System.out.println("I am a method from class C");
    }

    public static void main(String[] args) {
        C obj = new C();
        obj.display();
    }
}

Output:

I am a method from class C

2) When a class doesn’t provide implementation, then an error would occur.

Example:

interface A {
    default void display() {
        System.out.println("I am a method from interface A");
    }
}

interface B {
    default void display() {
        System.out.println("I am a method from interface B");
    }

}

class C implements A,B{

    public static void main(String[] args) {
        C obj = new C();
        obj.display();
    }
}

Error:

error: types A and B are incompatible;
class C implements A,B{
^
  class C inherits unrelated defaults for display() from types A and B

3) If an interface is having a default method and is extended by another interface which consists same default method, then the most recent inheriting interface’s version in the hierarchy is considered.

Example.

interface A {
    default void display() {
        System.out.println("I am a method from interface A");
    }
}

interface B extends A {
    default void display() {
        System.out.println("I am a method from interface B");
    }

}

class C implements A,B{

    public static void main(String[] args) {
        C obj = new C();
        obj.display();
    }
}

Output:

I am a method from interface B

Java also allows the privilege to explicitly refer to a particular interface’s default implementation.

InterfaceName.super.methodName( )

 

]]>
https://programmerbay.com/multiple-inheritance-in-java-with-program-example/feed/ 0
Multilevel Inheritance in Java with Program Example https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/ https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/#respond Fri, 19 Jan 2024 14:08:35 +0000 https://programmerbay.com/?p=9054 Multilevel inheritance is a type of inheritance where a subclass acts as a superclass of another class. In other words, when a class having a parent class, is extended by another class and forms a sequential chain, then it’s termed Multilevel inheritance. For instance, class A is extended by class B, and further class B is inherited by class C which acquires features of class A and class B.

multilevel inheritance in Java

In multilevel inheritance, a parent can have a single child only and at least require three classes arranged sequentially, forming a chain of parent-child relations.

Syntax:

class A {

}

class B extends A {

}

class C extends B {

}

Multilevel inheritance program in Java

Below are some programs provided to implement multilevel inheritance in Java.

Example 1. Program to implement multilevel Inheritance in Java

Program:

class Person {

    String getName(){
        return "ProgrammerBay";
    }
}

class Programmer extends Person{
    String getCodingLanguage(){
        return "Java";
    }
}

class Program extends  Programmer{
    int getLineOfCode(){
        return 20;
    }
    public static void main(String[] args) {
        Program program = new Program();
        System.out.println(" I am "+program.getName()+" and I code in "+ program.getCodingLanguage()+
                " . This program has "+program.getLineOfCode()+" lines");
    }
}

Output:

I am ProgrammerBay and I code in Java . This program has 20 lines

Explanation:

In the above code, we are having 3 classes named Person, Programmer and Program where class Program is inheriting class Programmer, further, class Programmer is extending class Person. As a result, the Program class’s got the functionalities of class Programmer and also class Person.

Example 2. Program to show real world example of multilevel inheritance in Java

Program:

class iPhone6 {
    void makeCalls(){
        System.out.println("Calling functionality.......");
    }
}

// Getting feature of previous iPhone model
class iPhone10 extends iPhone6{

    void unlockPhoneByFaceId(){
        System.out.println("Unlocking phone by face Id.......");
    }

}
// Getting feature of previous iPhone10
class iPhone12 extends iPhone10{

    void supportFor5GNetwork(){
        System.out.println("5G network support.......");
    }

    public static void main(String[] args) {
        iPhone12 iPhone = new iPhone12();
        iPhone.makeCalls();  // feature reused of iPhone 6 for iPhone 12
        iPhone.unlockPhoneByFaceId(); // feature reused of iPhone 10 for iPhone 12
        iPhone.supportFor5GNetwork(); // additional feature
    }
}

Output:

Calling functionality.......
Unlocking phone by face Id.......
5G network support.......

Explanation:

In the above code, we’ve tried to explain multilevel inheritance using the iPhone Models example. Just similar to the previous example, iPhone12 class is having the functionality of iPhone10 and iPhone6 classes. Because iPhone12 class is inheriting iPhone 10 class, further, iPhone10 is extending iPhone 6 class.

Example 3. Program to print order of constructor calling using multilevel Inheritance in Java

Program:

class Person {
    Person(){
        System.out.println("This is Person's class constructor");
    }

    void printName(){
        System.out.println("ProgrammerBay");
    }
}

class Programmer extends Person{
    Programmer(){
        System.out.println("This is Programmer's class constructor");
    }
    void printCodingLanguage(){
        System.out.println("Java");
    }
}

class Program extends  Programmer{
    Program(){
        System.out.println("This is Program's class constructor");
    }

    void printLineOfCode(){
        System.out.println(20);
    }
    public static void main(String[] args) {
        Program program = new Program();
        program.printName();
        program.printCodingLanguage();
        program.printLineOfCode();
    }
}

Output:

This is Person's class constructor
This is Programmer's class constructor
This is Program's class constructor
ProgrammerBay
Java
20

Explanation:

  1. In the above code, there are three classes named Person, Programmer, Program declared in which Person is extended by Programmer and Programmer is further inherited by Program class.
  2. Each class’s got a default constructor, where we are printing a message to identify the order of invocation.
  3. When the program’s object got created, the very first block executed was the Person class, after the Programmer’s constructor was called and at last Program’s constructor.
  4. In other words, the constructor of the foremost class in the chain is invoked first, then the constructor of immediate next class is called one by one, until it invokes the constructor of the class whose object is created

Frequently Asked Questions

What is multilevel Inheritance in java?

Multilevel Inheritance in java can be defined as an inheritance where a class extends another class, and further, that subclass is become a parent of another class by extending it

How is multilevel Inheritance implemented in Java?

It can be implemented using extends keyword where class A is extended by B, and further, C sequentially extends B.

Is multilevel Inheritance allowed in Java?

Yes, multilevel Inheritance is supported in Java.

What are the types of Inheritance in Java?

There are various types of inheritance supported by Java.
In the case of interfaces, Java supports 5 types of inheritance
which are Single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance.
In the case of classes, it limits to 3 types which are single, multilevel and hierarchical inheritance as hybrid and multiple inheritance is not supported in this.

]]>
https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/feed/ 0
TreeSet Class in Java With Program Example https://programmerbay.com/treeset-class-in-java-with-program-example/ https://programmerbay.com/treeset-class-in-java-with-program-example/#respond Sat, 15 Jul 2023 14:16:02 +0000 https://programmerbay.com/?p=9408 TreeSet is an implementation class of NavigableSet interface which is a child interface of SortedSet. It is a class in the collection framework that stores and manipulates elements in some sorting order. It represents self-balancing binary tree as its underlying data structure which makes it a good choice for search and retrieving operations.

Screenshot from 2023 07 10 23 23 20

Syntax:

Set<T> set = new TreeSet<T>();

It stores elements in natural sorting order using compareTo() method of Comparable interface. It also allows custom sorting order with the help of compare() method of Comparator interface.

It provides various methods that are inherited from Navigable,SortedSet and Set interface.

Point to remember:

1. It uses self balancing tree as its underlying data structure
2. It doesn’t allow Duplicate elements

3. It doesn’t preserve insertion order

4. It stores data in some sorting order
5. Only comparable or same type of elements are allowed

6. It is not thread safe

7. It provides non synchronised implementation of Set

TreeSet an implementation of Binary Search Tree

TreeSet class uses self balancing binary search tree as its underlying data structure which makes it one of the efficient implementations for storing large data set in ordered manner. It takes logarithmic average and worst case time when it comes to perform basic operations such as add, delete and search.

TreeSet is not Thread Safe

It is also important to know that TreeSet provides non synchornized implementation which allow multiple threads to access a tree set object concurrently. It can lead to uncertain behaviour as more than one threads can operate on that object at the same time. It is possible to make a tree set synchronized. With the help of Collection.synchronizedSortedSet() method we can encapsulate a set in a synchronized object or wrapper.

Syntax :

Set<T> treeSet = new TreeSet<>();
Set synchronized = Collections.synchronziedSet(treeSet);

TreeSet NULL Acceptance

If  a treeSet is non empty Set, then by default we are going to get null pointer exception while trying to insert null value. It occurs because of the comparison with other elements.

For empty TreeSet, null value can be accepted

Constructors of TreeSet Class

There are four constructors support by TreeSet class.

1) TreeSet()

A default constructor that creates an empty tree set object with default natural sorting order

TreeSet<T> t = new TreeSet<T>()

2) TreeSet(Comparator c)

It creates an empty tree set instance with custom specified order defined using Comparator .

TreeSet<T> t = new TreeSet(Comparator c);

3) TreeSet(Collection obj)

It creates a tree set instance with the elements present in the collection object and order them in nature order.

TreeSet<T> t = new TreeSet<>(Collection obj)

4) TreeSet(SortedSet obj)

Similar to previous constructor, the constructor accepts a collection object which is in this case, is SortedSet and creates an tree set instance with all the elements present in that collection in natural order.

TreeSet<T> t = new TreeSet<T>(Sorted obj)

Methods of TreeSet Class

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object
Method NameExplanation
comparator()Returns comparator object which is used to define custom sorting order on elements in the set or returns null if the set is using some natural order
subSet(T from, T to)It returns all the elements rangin from element "fromEle" to "toEle". If both the elements are same, then it would return empty set. It can throw IllegalArgumentException if the provided elements are not in range of the given set
headSet(elementObj)It returns all the elements lesser than the provided element. It can throw IllegalArgumentException if the provided elements are not in range of the given set
tailSet(elementObj)It returns all the elements greater than the provided element. It can throw IllegalArgumentException if the provided elements are not in range of the given set
first()It returns very first element from the given set
last()It returns last element from the given set
MethodsExplanation
lower(element)It returns greatest element that is lower than the given element
higher(element)It returns lowest element that is higher than the given element
floor(element)It returns greatest element that is lower than or equal to the given element
ceiling(element)It returns lowest element that is higher than or equal the given element
pollFirst()It returns and removes first element from the set
pollLast()It returns and removes last element from the set
descendingSet()It returns reverse view of the given set.

Comparable Interface Vs Comparator Interface

If the empty tree set is created with default constructor, then the elements should be of same type and comparable, otherwise, ClassCastingException would be triggered by the Java compiler. Objects that implements Comparable interface are called comparable.

Comparable Interface

  • It resides in Java.lang package
  • It contains only single method, named compareTo()
  • It returns int value, as it decides whether an element, greater, equal or smaller than other

obj1.compareTo(obj 2)

  1.  -ve obj1 should come before obj2
  2.  +ve obj1 should come after obj2
  3.  0 both obj1 and obj2 are equal

Comparator Interface

If a custom implementation is required, we can use Comparator, not Comparable.

  • It is used for customised sorting order
  •  It resides in Java.util packages
  •  It contains 2 methods, compare() and equals()
  •  compare() also returns int.
  • It uses same comparison approach as compareTo() method
  •  It is compulsory to provide implementation of compare method but, equals() implementation is optional as it’s root class method
  • Using Comparator, we can use non comparable objects in tree set

A tree set can have duplicate elements if we use Comparator to implement the sorting or insertion changes.

Java Program to arrange and print elements of TreeSet in descending order with the help of Comparator

Program:

import java.util.*;

public class SetExample implements Comparator<Integer>{
    public static void main(String[] args) {

        Set<Integer> treeSet = new TreeSet<>(new SetExample()); // creating a treeSet instance that holds integers

        // Adding elements to linked hash set
        treeSet.add(5);
        treeSet.add(1);

        treeSet.add(2);
        treeSet.add(100);
        treeSet.add(101);


        // Iterating using for each

        Iterator iterator = treeSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }
    
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2-o1;
    }
}

Output:

101
100
5
2
1

 

]]>
https://programmerbay.com/treeset-class-in-java-with-program-example/feed/ 0
LinkedHashSet Class in Java With Program Example https://programmerbay.com/linkedhashset-class-in-java-with-program-example/ https://programmerbay.com/linkedhashset-class-in-java-with-program-example/#respond Sat, 15 Jul 2023 13:56:36 +0000 https://programmerbay.com/?p=9406 LinkedHashet is an implementation class of the Set interface which also extends the HashSet class. It was introduced in Java 1.4 version. It behaves in the same manner as HashSet except that it preserves or maintains the insertion order of elements inserted in the set. In simple words, It is an implementation of the set interface that stores and manipulates an ordered collection of elements.
It simply means the order in which elements are inserted, can be retrieved in the same order.

Screenshot from 2023 07 10 23 23 20

Points to Remember:

1) Hash Table and Linked List are its underlying data structure

2) It extends HashSet class and implements Set interface
3) It preserves insertion order
4) It permits only unique elements, similar to HashSet
5) It allows at most single null value
6) It offers a constant time performance for all the basic operations
7) It is less expensive than HashSet when comes to iterating over elements

Syntax:

Set<T> set = new LinkedHashSet<T>();

It is an implementation class that uses hash table and linked list data structure as its underlying data structure. It differs from HashSet with the exception that it maintains a doubly linked list to all the elements. It preserves insertion order with the help of a linked list which defines iteration order and makes sure the elements must be retrieved in the same order as they were previously inserted. It allows a single null element. It provides constant time performance for the basic operations.

There are 4 constructors provided in LinkedHashSet class:

1) LinkedHashSet()

A default constructor to create an empty linked hash set with default initial capacity and load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>();

2) LinkedHashSet(collectionObj) 

It creates a new linked hash set having elements present in passed collection object.

ArrayList<T> list = new ArrayList<>();

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(list);

3) LinkedHashSet(int initialCapacity) :

It creates an empty linked hash set with specified capacity and default load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(4);

4) LinkedHashSet(int initialCapacity, float loadFactor):

It creates an empty linked hash set with mentioned capacity and load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(4,0.8);

Methods of LinkedHashSet Class

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Java Program to create LinkedHashSet instance and demonstrate its basic operations

Program:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {

        Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

        // Adding elements to linked hash set
        linkedHashSet.add(5);
        linkedHashSet.add(1);
        linkedHashSet.add(null);  // adding nul value
        linkedHashSet.add(100);

        // Displaying Stored elements
        System.out.println(linkedHashSet);

        // removing null element from linked hash set

        linkedHashSet.remove(null);

        //Displaying after removing null

        System.out.println(linkedHashSet);

        // iterating through hash set

        Iterator iterator = linkedHashSet.iterator(); // getting iterator object
        System.out.println("Iterating over all the element of linked hash set :: ");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }


    }
}

Output:

[5, 1, null, 100]
[5, 1, 100]
Iterating over all the element of linked hash set :: 
5
1
100

Basic Operations of LinkedHashSet

1) Adding element

HashLinkedSet supports add() and addAll() method to add elements in a given set

add(element) : It adds a given element to the set
addAll(collectionObj): It adds all the elements provided in collection object.

Java program to demonstrate add operation in LinkedHashSet

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

// Displaying Stored elements
System.out.println(linkedHashSet);

// add All method to add multiple elements

linkedHashSet.addAll(Arrays.asList(100,101,102,103));

//Displaying after addAll

System.out.println(linkedHashSet);


}
}

Output:

[5, 1]
[5, 1, 100, 101, 102, 103]

2) Removing element

There are two methods namely, remove() and removeAll() used for removing single or multiple elements from a set.
remove(element) : It removes the given element from the given set.
remove(collectionObj) : It removes all the elements present in the collection object from the given set.

Java program to demonstrate remove operation in LinkedHashSet

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

linkedHashSet.add(2);
linkedHashSet.add(100);
linkedHashSet.add(101);
linkedHashSet.add(102);
// Displaying Stored elements
System.out.println(linkedHashSet);

// removing single element the linked hash set

linkedHashSet.remove(2);

System.out.println("Removed 2 :: "+linkedHashSet);

// removeAll for remove multiple elements

linkedHashSet.removeAll(Arrays.asList(100,101,102));

//Displaying after removeAll

System.out.println("Removed 100, 101,102 from set :: "+linkedHashSet);


}
}

Output:

[5, 1, 2, 100, 101, 102]
Removed 2 :: [5, 1, 100, 101, 102]
Removed 100, 101,102 from set :: [5, 1]

3) Iterating over elements

There are multiple ways to iterate over a linked hash set. These are the following :-
1) iterator()
2) forEach()
3) Using Java 8 streams

Java program to demonstrate iteration operation over elements of a linked hash set object

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

linkedHashSet.add(2);
linkedHashSet.add(100);
linkedHashSet.add(101);

// Iterating using for each

System.out.println("Iterating using foreach :: ");
for (Integer element:
linkedHashSet) {
System.out.println(element);
}

// Iterating using iterator object
System.out.println("Iterating using iterator :: ");

Iterator iterator = linkedHashSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}

System.out.println("Iterating using stream :: ");

linkedHashSet.stream().forEach(e-> System.out.println(e));
}
}

 

Output:

Iterating using foreach ::
5
1
2
100
101
Iterating using iterator ::
5
1
2
100
101
Iterating using stream ::
5
1
2
100
101

 

]]>
https://programmerbay.com/linkedhashset-class-in-java-with-program-example/feed/ 0
HashSet Class in Java With Program Example https://programmerbay.com/hashset-class-in-java-with-program-example/ https://programmerbay.com/hashset-class-in-java-with-program-example/#respond Thu, 13 Jul 2023 17:43:58 +0000 https://programmerbay.com/?p=9366 Set interface doesn’t provide any additional method, as a result, implementation classes use only collection interface methods.
HashSet is an implementing class of Set interface and it represents Hash Table as its underlying data structure. It is a collection of unordered unique elements that don’t allow duplicates. It also doesn’t preserve insertion order as it uses hash code to store an element. Meaning, the elements are stored based on some hash values and can be retrieved in any order.

Screenshot from 2023 07 10 23 23 20

It uses several methods of Collection interface i.e. add(), remove(), contains(). The add() method returns false and doesn’t add an element if one tries to insert a duplicate element. The advantage of using HashSet, it makes searching faster.

It can store different types of objects and allows at most a single null value to hashSet.
It also implements the Serializable and Collneable interface.

Set is the best choice when the frequent search operation is required.

Syntax:

Set<String> set = new HashSet<String>();

Point to Remember :

  1. It doesn’t preserve insertion order
  2. It allows atmost single null value
  3. It can store various type of objects at the same time
  4. It uses hash table as its underlying data structure
  5. It is a best choice when frequent search operation is involved
  6. It doesn’t allow duplicate that makes it ideal for storing unique elements

 

Constructors of HashSet

There are 4 constructors in HashSet:

1) HashSet()

It is a default constructor that creates an empty Set with a default capacity of 16 elements and having default fill ratio 0.75.

HashSet<T> obj = new HashSet<>() :

Fill ratio/ Load Factor : It simply means after which ratio/ percentage, a new set should be created. For instance, if fill ratio is 0.75, then a new hashSet would be created after occupying 75% capacity of the set.

2) HashSet(int initialCapacity)

It creates an empty set with the provided initial capacity value with default fill ratio 0.75.

HashSet<T> h = new HashSet<>(int initialCapacity);

3) HashSet<T>(int initialCapacity, float loadFactor)

It creates an empty set with provided initial capacity and load factor.

HashSet<T> h = new HashSet<T>(int initialCapacity, float loadFactor);

4) HashSet<T>(Collection obj)

It creates a set with the collection elements passed in the constructor. It can be arrayList, linkedList or any other object that implements collection interface.

HashSet<T> h = new HashSet<T>(Collection obj);

Program to demonstrate creation of HashSet in Java

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        set.add("Duplicate");
        set.add("Duplicate");
        System.out.println(set);
    }
}

Output:

[Example, Duplicate, Programmerbay]

 

How HashSet or HashMap works in Java?

HashSet internally uses the HashMap constructor to create an empty set with a default capacity of 16 and 0.75 load factor.
When the add() method is called, again put() method of HashMap is also invoked where the element that is being added acts as a key and a constant value (PRESENT) acts as a value. When one tries to add the same element then, we all know, what would happen when one tries to add an element with the same key in a map, it would override or replace the existing key-value pair. That is why HashSet doesn’t allow duplicate elements.

Further, lets see the working of HashMap.

HashMap also adheres HashTable Alogrithm Internally.

When a HashMap object is created, JVM creates Hash Table which is nothing but an array of nodes or buckets internally concerning the capacity of the Set or Map. These buckets act as a node that connects like a linked list.
When an element is added or put in the object, a corresponding hashcode or hash is generated using hashCode() method.

Based on the Modular operator it identifies the index and stores the data in that bucket (consisting array of nodes) residing on that position.
If two elements are having same hashcode, then it would not directly be stored in the same bucket, instead, the equal() method will be used to check whether the two elements are the same or not. If both are evaluated as different, then it would be stored in the same bucket otherwise, it will be replaced.

The situation of having the same hash of two elements is also known as Hashing collision, to deal with it, the equals() method is internally used by JVM.

Methods in HashSet

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

]]>
https://programmerbay.com/hashset-class-in-java-with-program-example/feed/ 0
NavigableSet Interface in Java With Program Example https://programmerbay.com/navigableset-interface-in-java-with-program-example/ https://programmerbay.com/navigableset-interface-in-java-with-program-example/#respond Thu, 13 Jul 2023 12:45:27 +0000 https://programmerbay.com/?p=9390 NavigableSet is a child interface of SortedSet that provides navigation methods to navigate through a set. It showcases the same behaviour as SortedSet with some additional navigable attributes & behaviour. It provides several methods that are only applicable to the implementation classes of NavigrableSet interface such as lower(), floor(), and ceiling methods to get elements less than or equal, greater than or equal and greater than a given element.

Screenshot from 2023 07 10 23 23 20

TreeSet and ConncurrentSkipListSet are two implementation classes of the interface.
Syntax:

NavigableSet<T> navigableSet = new TreeSet<>();

How to create object of NavigabelSet ?

Navigable Set is an interface, in order to create an object of that type, it is compulsory to have a implementation class of the respective interface. In this case, TreeSet can be used to create instance that can be assigned to NavigableSet type.

program:

public class SetExample {
public static void main(String[] args) {

NavigableSet<String> navigableSet = new TreeSet<>();
// Adding elements to navigableSet set object
navigableSet.add("Example");
navigableSet.add("Code");
navigableSet.add("A");

// Displaying the output
System.out.println(navigableSet);

}
}

Output:

[A, Code, Example]

It also allows a set to traverse in both orders, either ascending using an iterator or descending order with the method descendingSet(). Considering performance-wise, traversing elements in ascending order is faster than the traversing descending order. There are some more additional methods namely pollFirst() and pollLast() to remove the first and last element (lowest and highest element) from the set and return it.

Methods of NavigableSet Interface

Below are the methods that is offered by NavigableSet interface

MethodsExplanation
lower(element)It returns greatest element that is lower than the given element
higher(element)It returns lowest element that is higher than the given element
floor(element)It returns greatest element that is lower than or equal to the given element
ceiling(element)It returns lowest element that is higher than or equal the given element
pollFirst()It returns and removes first element from the set
pollLast()It returns and removes last element from the set
descendingSet()It returns reverse view of the given set.

Below are the methods that is inherited from SortedSet.

Method NameExplanation
comparator()Returns comparator object which is used to define custom sorting order on elements in the set or returns null if the set is using some natural order
subSet(T from, T to)It returns all the elements rangin from element "fromEle" to "toEle". If both the elements are same, then it would return empty set. It can throw IllegalArgumentException if the provided elements are not in range of the given set
headSet(elementObj)It returns all the elements lesser than the provided element. It can throw IllegalArgumentException if the provided elements are not in range of the given set
tailSet(elementObj)It returns all the elements greater than the provided element. It can throw IllegalArgumentException if the provided elements are not in range of the given set
first()It returns very first element from the given set
last()It returns last element from the given set

Below are the methods that is inherited Set.

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

]]>
https://programmerbay.com/navigableset-interface-in-java-with-program-example/feed/ 0
SortedSet Interface in Java With Program Example https://programmerbay.com/sortedset-interface-in-java-with-program-example/ https://programmerbay.com/sortedset-interface-in-java-with-program-example/#respond Tue, 11 Jul 2023 17:19:23 +0000 https://programmerbay.com/?p=9389

SortedSet is an interface whose implementation class is TreeSet. With the help of implementation classes, we can assign its instance to sortedSet interface. Below is the example:

Program:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        SortedSet<String> sortedSet = new TreeSet<>() ;  // Creating sortedSet object

        // Adding elements to sorted set object
        sortedSet.add("Example");
        sortedSet.add("Code");
        sortedSet.add("A");

        // Displaying the output
        System.out.println(sortedSet);

        // Removing A element from the set
        sortedSet.remove("A");

        System.out.println(sortedSet);

        // printing first element from the set
        System.out.println(sortedSet.first());

        // printing last element from the set
        System.out.println(sortedSet.last());
    }
}

Output:

[A, Code, Example]
[Code, Example]
Code
Example

Methods of SortSet Interface

Existing methods from Set interface
Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

]]>
https://programmerbay.com/sortedset-interface-in-java-with-program-example/feed/ 0
Set Interface In Java With Program Example https://programmerbay.com/set-interface-in-java-with-program-example/ https://programmerbay.com/set-interface-in-java-with-program-example/#respond Mon, 10 Jul 2023 17:57:29 +0000 https://programmerbay.com/?p=9365 Set is a child interface of the Collection interface that represents an unordered collection where each element is unique and cannot be repeated. It only consists of methods inherited from its parent interface and doesn’t allow duplicate elements. Further, if someone tries to add a duplicate via add() method, then it would return false, signifying the given element is not able to get added. It is part of java.util package.

Screenshot from 2023 07 10 23 23 20
It provides several essential methods that can be used to store, manipulate and search elements in a given set. It depicts a mathematical set and provides its abstraction.

There are various methods which implement the Set interface, including HashSet, LinkedHashSet and TreeSet.
SortedSet and NavigableSet interfaces further extend Set Interface that provides additional behaviour and different implementation to the existing method. NavigableSet is a child interface of SortedSet that provides navigational methods to navigate through a Set. It has a child class named TreeSet which is an implementation of the self-balancing tree.

How to declare and initialise a Set Object in Java?

Set interface provides specification only, in order to create its object, one requires its implementing class i.e HashSet,TreeSet, in order to create an object. With the help of Generics, we can specify the type of object that a Set Collection can store.

Set<T> set = new HashSet<T> ();

Point to Remember:

  • It doesn’t preserve order of inserted elements
  • It allows at most single null element
  •  It doesn’t allow duplicate elements
  • It can have elements of different types

Methods of Set Interface

The methods supported by Set Interface are listed below :

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Java Program to demonstrate working of Set interface

Program:

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>() ;  // Creating set object
        set.add("The");
        set.add("Programmerbay");
        set.add("Code");
        set.add("Example");

        System.out.println("Printing Added element :: "+set);
        set.add("Code");  //  Adding duplicate element
        System.out.println("Duplicate element not present :: "+set);
        set.remove("Example");  //  Removing duplicate element
        System.out.println("Removing 'Example' element :: "+set);


    }
}

Output:

Printing Added element :: [The, Example, Code, Programmerbay]
Duplicate element not present :: [The, Example, Code, Programmerbay]
Removing 'Example' element :: [The, Code, Programmerbay]

Basic Operations Supported by Set and Its implementing Classes

1) Add Elements :

Set interface specifies add(object) and addAll(CollectionObj) to add elements to a set. It doesn’t preserves insertion order of inserted elements. In contrast, it uses hashing mechanism to store elements where a hash of an element is generated and stored in a hash table. As mentioned before, it doesn’t allow duplicates, but accepts atmost single null value.

Java program to add single element and multiple elements in a Set using add() and addAll() method

Program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object
Collection<String> collection = List.of( "Another","Collection","inserted");

set.add("Programmerbay");

System.out.println("Single Added element :: "+set);

set.addAll(collection); // Adding collection elements, but order will not be preserved

System.out.println("Collection added to set :: "+ set);

}
}

Output:

Single Added element :: [Programmerbay]
Collection added to set :: [inserted, Collection, Programmerbay, Another]

2) Remove Elements:

Set interface offers three methods for this, however, all have different use cases.
1) remove() -> It removes a single element
2) removeAll() -> It accepts a collection object and removes all elements that match the targeted set.
3) retainAll () -> Opposite to removeAll(), it accepts a collection object and persists only those elements that match with the provided collection, other elements that are present in the targeted set get removed.

Java program to remove single element and multiple elements in a Set using remove() and removeAll() method

Program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object
Collection<String> retainObjs = List.of("Programmerbay","Code");
Collection<String> removeAllObj = List.of("Remove1","Remove2");

// Adding random elements
set.add("Remove Me");
set.add("Remove1");
set.add("Remove2");
set.add("Programmerbay");
set.add("Example");
set.add("The");
set.add("Code");


System.out.println("Elements :: "+set);

// removing 'remove Me' from the list
set.remove("Remove Me");

System.out.println("After single remove :: "+set);

set.removeAll(removeAllObj); // remove1 and remove2 stored in removeAllObj would remove elements in set

System.out.println("after removeAll() :: "+ set);

set.retainAll(retainObjs); // Programmerbay and Code stored in reainAllObj would store elements and remove others from the set

System.out.println("after retainAll() :: "+ set);

}
}

Output:

Elements :: [The, Remove1, Remove2, Remove Me, Example, Code, Programmerbay]
After single remove :: [The, Remove1, Remove2, Example, Code, Programmerbay]
after removeAll() :: [The, Example, Code, Programmerbay]
after retainAll() :: [Code, Programmerbay]

4) Iterate over Elements:

There are multiple ways to iterate over elements of a set. These are the following:
1) using iterator
2) Using forEach()
3) Using Java 8 Stream

Java program to iterate over elements of a set.

program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object

// Adding random elements
set.add("Remove Me");
set.add("Remove1");
set.add("Remove2");
set.add("Programmerbay");
set.add("Example");
set.add("The");
set.add("Code");

Iterator iterator = set.iterator(); // fetching iterator object of the set

System.out.println("Iterating through iterator object :: ");
while (iterator.hasNext()){
System.out.println(iterator.next());
}


// using for each
System.out.println("Iterating through for each loop :: ");

for (String element:
set) {
System.out.println( element);
}

// using Java 8 Stream
System.out.println("Iterating through using java 8 stream :: ");

set.stream().forEach(e -> System.out.println("element :: "+ e));

}
}

Output:

Iterating through iterator object ::
The
Remove1
Remove2
Remove Me
Example
Code
Programmerbay
Iterating through for each loop ::
The
Remove1
Remove2
Remove Me
Example
Code
Programmerbay
Iterating through using java 8 stream ::
element :: The
element :: Remove1
element :: Remove2
element :: Remove Me
element :: Example
element :: Code
element :: Programmerbay


Implementing Classes of Set Interface

HashSet class : Hashset class is a implementing class of Set interface that uses hash table as its underlying data structure. It doesn’t preserves insertion order,meaning, the order in which elements are inserted may differ as it hash code to insert data. It accepts null values.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Example, Programmerbay]

LinkedHashSet class : It also implements Set interface and exhibits the behavior of doubly linked list. Unlike HashSet, it preserves insertion order.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new LinkedHashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Programmerbay, Example]

 

TreeSet class : It is a implementation class of SortedSet interface. It resembles tree data structure to store and manage data. It stores data in natural sorting order.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new TreeSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Example, Programmerbay]

 

 

 

]]>
https://programmerbay.com/set-interface-in-java-with-program-example/feed/ 0
LinkedList Class in Java with Program Example https://programmerbay.com/linkedlist-class-in-java-with-program-example/ https://programmerbay.com/linkedlist-class-in-java-with-program-example/#respond Thu, 06 Jul 2023 18:12:36 +0000 https://programmerbay.com/?p=9361 LinkedList is a child class of List and Queue interface. It owns the behaviour of Doubly Linked List and represents it as its underlying data structure . It is ideal to use when insertion or deletion are the frequent operations. In Linked List, elements are not stored in sequential manner,instead, each element in a Linked List is stored as a separate node, pointing to the previous and next elements in the list. The problem with linked list is, its performance degrades when it comes to retrieve operation or fetching an element.

Screenshot from 2023 07 06 22 46 01

Point to Remember:

1. It preserves insertion order and duplicates are allowed.

2. It accepts different types of objects and null insertions.

3. Similar to ArrayList, it is growable in nature, meaning, its size can shrink or grow dynamically.

4. It is best choice when insertion and deletion operations are involved mostly.

5. It resembles doubly linked list data structure which provides flexibility to implement other algorithms and data structure such as Stack,Queue and more.

6. It has the worst performance in case of fetching or accessing an element from the list as it provides linear-time performance.

7. It implements Serializable and Clonable interface but not RandomAccess interface.

8. It is not thread-safe, which means that multiple threads cannot safely access and modify the list at the same time.

9. It becomes slower than other List implementations when it comes to traversing over elements.

Method of Linked List Class

Linked List implements List and Deque interface. Therefore, there are several methods implemented by this class.

Below are the methods inherited from Deque.

MethodExplanation
addFirst(element)It adds the given element at first position in the given list
addLast(element)It adds the given element at the end in the given list
element()It returns head of the given list
getFirst()It returns first elements of a linked list
getLast()It returns last elements of a linked list
offer(element)It adds the given element at the end of the list
offerFirst(element)It adds element at the beginning of a list
offerLast(element)It adds element at the end of a list
peek()It returns head or first element of the given list
peekFirst()It returns first element, if the list is empty, returns null
peekLast()It returns last element, if the list is empty, returns null
poll()It removes and returns first element of the given list
pollFirst()It removes and returns first element, if the list is empty, returns null
pollLast()It removes and returns last element, if the list is empty, returns null
pop()It pops an element from the list, acting as Stack
push(E e)It pushes an element from the list, acting as Stack
remove()It returns and remove the head of a linked list
removeFirst()It removes and returns first element
removeFirstOccurrence(Object o)It removes first occurrences of the given element
removeLast()It removes and returns last element
removeLastOccurrence(Object o)It removes last occurrences of the given element

Below are the methods is from List interface.

MethodsExplanation
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Constructors of Linked List

There are two constructor present in Linked list class. These constructors are explained below :-

1) new LinkeList()

It is a default constructor that creates an empty linked list. Unlike ArrayList, it doesn’t have capacity issue.

Syntax:

LinkedList<T> l = new LinkeList<>() :

2) new LinkedList(Collection obj)

It creates a linked list instance, consisting elements of the given collection object.

LinkedList l = new LinkedList(Collection obJ);

Operations in LinkedList Class

1) Add an element

There are several methods provided by LinkedList class to add an element, such as add(), addFirst(),addList(),push(),offerFirst() and more.
Among all, add() and addAll() methods are most commonly used methods to perform add operation.

Program:

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> linkedList = new ArrayList<>(); // creating instance of linked list

// Adding elements to linked list

linkedList.add("Programmerbay");
linkedList.add("Example");

// Displaying elements of the list
System.out.println(linkedList);

// addAll method to add list of elements
linkedList.addAll(Arrays.asList("element1","element2"));
System.out.println(linkedList);

}
}

Output:

[Programmerbay, Example]
[Programmerbay, Example, element1, element2]

2) Replace an element

LinkedList supports index based access which provides it the capability to update or replace an element at given position .
set() method is used for the purpose. Below is the code example.

Program:

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> linkedList = new ArrayList<>(); // creating instance of linked list

// Adding elements to linked list

linkedList.add("Programmerbay");
linkedList.add("Example");

// Displaying elements of the list
System.out.println(linkedList);

// set method to replace an element with new one
linkedList.set(1,"Removed") ; // Example would be replaced with Removed

System.out.println(linkedList);

}
}

Output:

[Programmerbay, Example]
[Programmerbay, Removed]

3) Remove an element

Like several add() methods, LinkedList supports several methods to remove an element from a list i.e remove(),removeFirst(),removeLast() , pop() and more. The most commonly used methods are remove() and removeAll(). Below is a code example

Program:

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> linkedList = new ArrayList<>(); // creating instance of linked list

// Adding elements to linked list

linkedList.add("Programmerbay");
linkedList.add("Example");
linkedList.add("Test");


// Displaying elements of the list
System.out.println(linkedList);

// remove(element) method to remove the given element
linkedList.remove("Test"); // element Test would be removed

System.out.println(linkedList);


// remove(index) method to remove element from the given index

linkedList.remove(1); // element would be removed, sitting at 1st index which is example in this case
System.out.println(linkedList);
}
}

Output:

[Programmerbay, Example, Test]
[Programmerbay, Example]
[Programmerbay]

4) Traverse or iterate over elements

Like other implementation classes of List interface, elements of a linked list can also be traversed through various ways, iterator object and forEach are some of them.

With the help of iterator, we can traverse through all the elements in the given linked list. Also, enhanced for loop can also be used to loop through elements. Below are the code example.

Program:

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> linkedList = new ArrayList<>(); // creating instance of linked list

// Adding elements to linked list

linkedList.add("Programmerbay");
linkedList.add("Example");
linkedList.add("Test");

// traversing element using iterator object
System.out.println("Traversing using iterator :: ");

Iterator iterator = linkedList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}

// traversing element using for each method
System.out.println("Traversing using for each :: ");
for (String str:
linkedList) {
System.out.println(str);
}


}
}

Output:

Traversing using iterator ::
Programmerbay
Example
Test
Traversing using for each ::
Programmerbay
Example
Test

5) Converting List to Array

toArray() method provides the capability to convert a given linked list to array of objects. Below is the code example.

Program:

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> linkedList = new ArrayList<>(); // creating instance of linked list
linkedList.add("Programmerbay");

System.out.println("List view :: "+ linkedList);
Object[] array = linkedList.toArray();

System.out.println("Array view :: ");
for (Object obj:
array) {
System.out.print(obj);
}
}
}

Output:

List view :: [Programmerbay]
Array view :: 
Programmerbay

 

]]>
https://programmerbay.com/linkedlist-class-in-java-with-program-example/feed/ 0
Stack Class in Java with Program Example https://programmerbay.com/stack-class-in-java-with-program-example/ https://programmerbay.com/stack-class-in-java-with-program-example/#respond Wed, 05 Jul 2023 16:18:55 +0000 https://programmerbay.com/?p=9354 Stack extends Vector class that implements Last in first out (LIFO) data structure, introduced in JDK 1.0. The data structure specifies the last element to be added to the stack, is the first one to be removed. It is a subclass of the Vector class that enables it to inherit all the attributes and methods of its parent class. It is considered as a legacy class as it exist even before the collection framework and it is re-engineered to support the collection.

Screenshot from 2023 07 04 19 23 17

Further, it provides only a default constructor to create an empty stack object.

One of the main use case of the Stack class is to reverse a sequence of elements. This can be done by pushing elements onto the stack and then popping them off one by one from the top.

The collection class provides various methods for manipulating elements present in the stack, such as push(), pop(), peek(), and empty().

Methods Of Stack Class

push(): The push method is used to add an element to the top of the stack

pop(): The pop method is used to remove and return the element at the top.

peek(): The peek method returns the element at the top without removing it.

empty(): It returns true if the stack is empty, otherwise, false.

search(): It searches an element, and returns offset, otherwise, -1 to signify not found.

Other Inherited Methods

MethodsExplanation
addElement(T obj)Inserts an element to the end of the list.
removeElement( T obj)Removes the very first occurrence of the given element
trimToSize()Reduces the capacity of the given vector to the current size
ensureCapacity(int minCapacity)Increases the capacity to ensure that the list can hold at least the specified number of elements
setSize()Set the size of the given vector, storing null values to new empty spaces
capacity()Returns the current capacity of the vector
insertElementAt(T obj, int indx)Inserts the given element at the specified position, moving elements greater than that index by 1
removeElementAt(int indx)Deletes the element at the specified index
setElementAt(T obj, int indx)Replaces the element at the specified position with the specified element
elementAt(int indx)Returns the element at the given position
firstElement()Returns the first element in the list
lastElement()Returns the last element in the list
copyInto(Object[] o)Copies elements to the given arrays passed as parameter
indexOf(T o)Returns the index of the first occurrence of the specified element
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Here’s a program example to reverse a sequence of integers using Stack:

Program: 

import java.util.Stack;

public class Main
{
  public static void main (String[]args)
  {
    Stack < Integer > stack = new Stack <> ();
    stack.push (1);
    stack.push (2);
    stack.push (3);
    stack.push (4);
    while (!stack.empty ())
      {
  System.out.println ("Element :: "+ stack.pop ());
      }
  }
}

Output:

Element :: 4
Element :: 3
Element :: 2
Element :: 1

Over Stack class, the Deque interface should be used as it provides a more complete and flexible API. The Deque interface extends the Queue interface and supports both LIFO and First-In-First-Out (FIFO) operations. The ArrayDeque class implements the Deque interface which is a resizable array and is a good choice for most use cases.

Here’s a program code to reverse a sequence of integers  using the ArrayDeque class:
Program:
import java.util.ArrayDeque;
public class Main
{
  public static void main (String[]args)
  {
    ArrayDeque < Integer > deque = new ArrayDeque <> ();
    deque.push (1);
    deque.push (2);
    deque.push (3);
    deque.push (4);
    while (!deque.isEmpty ())
      {
  System.out.println ("Element :: "+deque.pop ());
      }
  }
}
Output:
Element :: 4
Element :: 3
Element :: 2
Element :: 1

 

]]>
https://programmerbay.com/stack-class-in-java-with-program-example/feed/ 0