Reputation: 31
package set;
import java.util.*;
public class Set
{
public static void main(String[] args)
{
String [] things = {"appple", "bob", "ham", "bob", "bacon"};
List<String> list = Arrays.asList(things);
System.out.printf("%s ", list);
System.out.println();
Set<String> set = new HashSet<String>(list);
System.out.printf("%s ", set);
}
}
When I try to run this program I keep getting this error for my set declaration. What am I doing wrong?
Upvotes: 3
Views: 3343
Reputation: 26077
Though not a good idea to name the classes that are already present in Java API etc.
Adding this will be enough
java.util.Set<String> set = new HashSet<String>(list);
Still you make some change to the existing
package set;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class Set {
public static void main(String[] args) {
String[] things = { "appple", "bob", "ham", "bob", "bacon" };
List<String> list = Arrays.asList(things);
System.out.printf("%s ", list);
System.out.println();
java.util.Set<String> set = new HashSet<String>(list);
System.out.printf("%s ", set);
}
}
Upvotes: 0
Reputation: 201497
You have shadowed the java.util.Set
import by naming your own local class Set
(set.Set
has a higher scope visibility and isn't generic). You could rename set.Set
, or use the fully qualified name (and the diamond operator <>
). Change
Set<String> set = new HashSet<String>(list);
to something like
java.util.Set<String> set = new HashSet<>(list);
Upvotes: 0
Reputation: 206926
You named your own class Set
, hiding the standard class Set
in package java.util
.
Rename your class to something else than Set
.
Upvotes: 1
Reputation: 393966
Rename your public class Set
class to a name that doesn't hide java.util.Set
.
Your custom Set
class doesn't take any type parameters. That's why Set<String>
doesn't pass compilation.
For example:
package set;
import java.util.*;
public class SetTest
{
public static void main(String[] args)
{
String [] things = {"appple", "bob", "ham", "bob", "bacon"};
List<String> list = Arrays.asList(things);
System.out.printf("%s ", list);
System.out.println();
Set<String> set = new HashSet<String>(list);
System.out.printf("%s ", set);
}
}
Upvotes: 3