Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create Set from String array

Tags:

java

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?

like image 579
janos Avatar asked Dec 19 '14 20:12

janos


3 Answers

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));
}
like image 61
Vogel612 Avatar answered Oct 24 '22 03:10

Vogel612


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

like image 30
Abhijeet Kushe Avatar answered Oct 24 '22 01:10

Abhijeet Kushe


Other answers have addressed the cause, but wouldn't it be better to simply rename the parameter to avoid the shadowing?

like image 37
Edward Avatar answered Oct 24 '22 03:10

Edward