LinkedHashSet toArray(K) in Java

toArray(K): This method is available in java.util.LinkedHashSet class of Java.

Syntax:

<K> K[] java.util.HashSet.toArray(K[] a)

This method takes one argument. This method returns an array containing all of the elements in this set.

Parameters: One parameter is required for this method.

a: the array into which the elements of this set are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Returns: an array containing all the elements in this set.

Exceptions: NA

Approach

Java

import java.util.Arrays;
import java.util.LinkedHashSet;

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

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

        linkedHashSet.add("Hello");
        linkedHashSet.add("Java");
        String array[] = { "Hello", "C++" };
        System.out.println(Arrays.toString(
linkedHashSet.toArray(array)));

    }
}

Output:

[Hello, Java]


No comments:

Post a Comment