Unable to create Set from String array

I looked at the screen for the last 5 minutes and cannot understand what I am doing wrong:

class Example { private final Set<String> values; public Example(String... values) { values = new HashSet<String>(Arrays.asList(values)); } } 

I am surprised why String[] cannot be converted to List<String> to initialize a HashSet<String> with it.

I get a build error:

 incompatible types: java.util.HashSet<java.lang.String> cannot be converted to java.lang.String[] 

What happened to my assignment?

+6
source share
4 answers

You are not qualified to access a private field. You are currently 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 further reduced by using the Diamond Operator, which is available since Java 7:

 public Example(String... values) { this.values = new HashSet<>(Arrays.asList(values)); } 
+9
source

Here 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) option before the assignment. When using var args, you are exposing a contract that will allow your clients to create a valid Example object without any arguments. If you want to avoid this, then simply use the String [] values ​​directly and throw an exception if it is null

+3
source

Other answers touched on the reason, but is it not better to simply rename the parameter to avoid shading?

+3
source

Use this.values ​​inside the constructor instead of the value, because the constructor parameter is a string array, and you are trying to convert a list to an array.

this.values ​​= ......

0
source

Source: https://habr.com/ru/post/979957/


All Articles