gpt4 book ai didi

java - 为最终变量分配函数返回类型

转载 作者:行者123 更新时间:2023-12-01 22:32:39 24 4
gpt4 key购买 nike

在java中,我尝试用函数返回值分配最终变量。但我得到了编译错误。谁能帮我看看是什么原因导致了这里的错误?

代码是这样的:

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>();
}
}
}

最佳答案

private static final set<String> set1 = getSet();

set1最终,这意味着它无法更改。

但是,

set1=new HashSet<String>(vactor1);

set1= new HashSet<String>();

正在努力改变它。请参阅JLS 4.12.4. final Variables :

A variable can be declared final. A final variable may only be assigned to once. Declaring a variable final 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.

我不知道是否是拼写错误,但是 static 应该全部小写,而不是 Static

关于java - 为最终变量分配函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27385798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com