knjk04
knjk04

Reputation: 115

How to add Strings to a LinkedHashSet?

LinkedHashSet lHs = new LinkedHashSet();
lHs.add("Beta");

When compiling the above (tutorialspoint uses a similar approach), I get the error:

The method add(String) is undefined for the type LinkedHashSet

And if it's generic (which I think it is from its class declaration):

LinkedHashSet<String> lHs = new LinkedHashSet<String>();
lHs.add("Beta");

then I get the error:

The type LinkedHashSet is not generic; it cannot be parameterized with arguments

From the Java docs, it seems that LinkedHashSet should work with the generic version because it extends HashSet, and HashSet works with add().

How do I add a String to a LinkedHashSet? Do I need to make my own overloaded add() method to include Strings?

See whole program here

Upvotes: 1

Views: 1371

Answers (1)

Eran
Eran

Reputation: 393846

Looking at your code:

class LinkedHashSet {

    public static void main(String[] args) {
        //LinkedHashSet<String> lHs = new LinkedHashSet<String>();
        LinkedHashSet lHs = new LinkedHashSet();

        lHs.add("Beta");
        lHs.add("Alpha");
        lHs.add("Eta");
        lHs.add("Gamma");
        lHs.add("Epsilon");
        lHs.add("Omega");

        System.out.println(lHs);
    }
}

The class name containing your code is named LinkedHashSet, which hides java.util.LinkedHashSet. Your class has no add method, and no generic type parameter. Hence the errors.

You should rename it. And you should use the generic declaration (LinkedHashSet<String> lHs = new LinkedHashSet<String>(); or Set<String> lHs = new LinkedHashSet<>();).

Upvotes: 3

Related Questions