Home > database >  Copying of objects from one set to another set in Collections Framework
Copying of objects from one set to another set in Collections Framework

Time:08-14

I was following the documentation about the differences between HashSet, LinkedHashSet and treeset and then I saw this program which was about copying of objects from one set to another, and I did follow but I couldn't understand it.

public class CopySetInJava {
    
    public static void main(String[] args) {
        
        HashSet<String> set = new HashSet<String>(Arrays.asList("List", "Map", "Graph"));
        
        System.out.println("Source Set: "   set);
        
        Set<String> Copy = CopySetInJava.copy(set);
        System.out.println("Copy of HashSet is: "   Copy);
        
    } 
    
    // This is the part I didn't understand
    public static <T> Set<T> copy(Set<T> set){
        return new LinkedHashSet<T>(set);
    }
}

CodePudding user response:

The constructors of the concrete implementations in the Java Collections framework will copy any Collection object you pass as a parameter.

CodePudding user response:

Set is an interface and LinkedHashSet is its implementation.
As per the LinkedHashSet API documentation:

public LinkedHashSet​(Collection<? extends E> c)

Constructs a new linked hash set with the same elements as the specified collection. The linked hash set is created with an initial capacity sufficient to hold the elements in the specified collection and the default load factor (0.75).

Type 'T' generic in copy method is defining the contract for your input argument and return type. Your return type 'Set<T>' can be modified to 'LinkedHashSet​<T>' and it should still function the same.

  • Related