简体   繁体   English

Java使用非final变量来设置final变量

[英]Java use of non-final variable to set final variable

This is probably a dumb question, but I'll risk asking it anyway. 这可能是一个愚蠢的问题,但无论如何我都会冒这个问题。

Often I need to create a final variable for use somewhere else and the value of that variable will need to be set based on some condition. 通常我需要创建一个final变量以供其他地方使用,并且需要根据某些条件设置该变量的值。 This is how I typically do it: 这就是我通常这样做的方式:

String notFinalVersion = null;
if (someThing == 1) {
    notFinalVersion = "The value was 1.";
} else {
    notFinalVersion = "The value is not 1.";
}
final String finalVersion = notFinalVersion;

I can then use the variable finalVersion where I need to. 然后我可以在需要的地方使用变量finalVersion But, this just seems somehow wrong. 但是,这似乎有些不对劲。 Is there a better way to do this? 有一个更好的方法吗?

Edit: By "better", I meant that I was looking for a method for defining the final variable that did not require that I create an extra variable. 编辑:通过“更好”,我的意思是我正在寻找一种方法来定义最终变量,不需要我创建一个额外的变量。 I knew that creating an extra variable was inefficient and not a good practice, and I was positive that there must be a way of doing what needed to be done without the extra steps. 我知道创建一个额外的变量是低效的而不是一个好的做法,而且我很肯定必须有一种方法可以在没有额外步骤的情况下完成所需的工作。

I received an answer, which I have marked as accepted. 我收到了一个答案,我已将其标记为已接受。 As I stated in my comment, I had originally tried the solution provided, but received an error from Eclipse. 正如我在评论中所述,我最初尝试过提供的解决方案,但收到了Eclipse的错误。 I must have either typed it incorrectly the first time, or Eclipse has something of a "hiccup". 我必须在第一次输入错误,或者Eclipse有一些“打嗝”。

I accept that there are many ways of doing something and that what one person will accept as the best way is not what someone else would consider. 我接受有许多方法可以做某事,一个人接受的最佳方式不是别人会考虑的。 However, all of the answers included here, were clear and to the point and, I feel, solved my problem. 但是,这里包含的所有答案都很明确,而且我觉得,解决了我的问题。

You can declare a final variable and not assign it yet, as long as it is definitely assigned before you use it. 您可以声明一个final变量而不是分配它,只要它在您使用之前已经明确分配。 Don't assign it null to begin with, else it will be definitely assigned already. 不要将它分配为null ,否则它将被明确分配。 Assign it as you are already doing with your if / else blocks, and you'll be fine. 像你已经使用if / elseelse分配它,你会没事的。

final String finalVersion;
if (someThing == 1) {
    finalVersion = "The value was 1.";
} else {
    finalVersion = "The value is not 1.";
}

除了@ rgettman的答案,对于这种情况你可以使用三元运算符

final String finalVersion = someThing == 1 ? "The value was 1." : "The value is not 1.";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM