I've been staring at the screen the last 5 minutes and can't seem to figure out what I'm doing wrong:
class Example {
private final Set<String> values;
public Example(String... values) {
values = new HashSet<String>(Arrays.asList(values));
}
}
I'm surprised why the String[]
cannot be converted to List<String>
to initialize the HashSet<String>
with it.
I'm getting the build error:
incompatible types: java.util.HashSet<java.lang.String> cannot be converted to java.lang.String[]
What's wrong with my assignment?
You're missing a qualification to actually access the private field. Currently you're trying to reassign the parameter passed to the constructor. Instead you should use the following code:
public Example(String... values) {
this.values = new HashSet<String>(Arrays.asList(values));
}
This can be shortened even further by using the "Diamond Operator", which is avaliable since Java 7:
public Example(String... values) {
this.values = new HashSet<>(Arrays.asList(values));
}
This is how you can do it
if(values != null)
this.values = new HashSet<>(Arrays.asList(values));
else
this.values = Collections.emptySet();
Add the if(values != null) check before the assignment.Whenever you use var args you are exposing a contract which will permit your clients to create an valid Example object without any arguments.If you want to avoid that from happening then just use String[] values directly and throw an exception incase if it is null
Other answers have addressed the cause, but wouldn't it be better to simply rename the parameter to avoid the shadowing?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With