Create New LinkedHashSet objects – Java LinkedHashSet Constructors

This example shows how to create new objects of LinkedHashSet in Java using the constructor. This example also shows how to use various LinkedHashSet constructors.

How to create new objects of LinkedHashSet in Java?

The LinkedHashSet class in Java provides several constructors using which we can create new objects of it as given below.

How to create a new and empty LinkedHashSet object?

The default LinkedHashSet constructor creates a new and empty set object.

The set created using this constructor will have a default initial capacity of 16 and a load factor of 0.75.

The above statement will create a new LinkedHashSet object of type Integer.

How to create a new LinkedHashSet object with custom initial capacity and load factor?

The default initial capacity of the LinkedHashSet is 16. If you want to change that, you can use the below given overloaded constructor provided by the LinkedHashSet class.

It creates a new set object having the specified initial capacity and a default load factor of 0.75.

If you want to specify both, the initial capacity and a load factor, you can use below given constructor.

It creates a new LinkedHashSet object with the specified initial capacity and load factor.

The above statement will create a new LinkedHashSet object with 25 initial capacity and load factor 0f 0.8.

How to create a new LinkedHashSet object from another collection object?

The LinkedHashSet class offers a constructor that accepts a collection object.

It creates a new linked hash set object having the same elements as the specified collection object. The initial capacity, in this case, will be large enough to hold all the elements of the specified collection and the load factor will be the default i.e. 0.75.

We can convert any collection to the linked hash set object using this constructor. The below given example shows how to convert ArrayList to LinkedHashSet object using this constructor.

Output

As we can see from the output above, the element “Monday” was only added once from the ArrayList object. Since the LinkedHashSet class is an implementation of the Set interface, it does not allow duplicate elements.

This example is a part of the Java LinkedHashSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 LinkedHashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping