Reputation: 31
In java i tried to assign the final variable with the function return value. But i got the compilation errors. Can anyone help me what is causing the errors here?
the code is like this:
public class A{
private static final set<String> set1 = getSet();
private Static Set<String> getSet(){
Vector<String> vector1 = getVector();//some function which return the Vector of type String
if(vector1!=null){
set1=new HashSet<String>(vactor1);
}
else{
set1= new HashSet<String>();
}
}
}
Upvotes: 0
Views: 448
Reputation: 31699
Your statement
private static final Set<String> set1 = getSet();
means this: It calls a method getSet
, which it expects to return a value, and then it assigns the returned value into set1
. (Note that it needs to be Set
, not set
.)
For this to work, getSet
actually has to return a value, using the return
statement. So instead of
set1=new HashSet<String>(vactor1);
the statement should be
return new HashSet<String>(vector1); // make sure vector1 is spelled correctly
and similarly with the other set1=
statement in getSet
.
Upvotes: 1
Reputation: 95968
private static final set<String> set1 = getSet();
set1
is final
, meaning that it cannot be changed.
However,
set1=new HashSet<String>(vactor1);
and
set1= new HashSet<String>();
are trying to change it. See JLS 4.12.4. final Variables:
A variable can be declared
final
. Afinal
variable may only be assigned to once. Declaring a variablefinal
can serve as useful documentation that its value will not change and can help avoid programming errors.It is a compile-time error if a
final
variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.
I don't know if it's a typo or not, but static
should be all lower-case, not Static
.
Upvotes: 3