Java 如何检查变量是否已初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2623125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:00:50  来源:igfitidea点击:

How do I check if a variable has been initialized

java

提问by Javier Parra

First of all, I'm fairly new to Java, so sorry if this question is utterly simple.

首先,我对 Java 还很陌生,如果这个问题非常简单,我很抱歉。

The thing is: I have a String[] smade by splitting a String in which every item is a number. I want to cast the items of sinto a int[] n.

问题是:我有一个String[] s通过拆分一个字符串来制作的,其中每个项目都是一个数字。我想将 的项目s转换为int[] n.

s[0]contains the number of items that nwill hold, effectively s.length-1. I'm trying to do this using a foreach loop:

s[0]包含n有效的项目数s.length-1。我正在尝试使用 foreach 循环来做到这一点:

int[] n;
for(String num: s){
    //if(n is not initialized){
        n = new int[(int) num];
        continue;
    }
    n[n.length] = (int) num;
}

Now, I realize that I could use something like this:

现在,我意识到我可以使用这样的东西:

int[] n = new int[(int) s[0]];
for(int i=1; i < s.length; i++){
    n[i-1] = (int) s[i];
}

But I'm sure that I will be faced with that "if n is not initialized initialize it" problem in the future.

但我敢肯定,我将来会面临“如果 n 未初始化,则对其进行初始化”的问题。

采纳答案by erickson

You can't cast a Stringto an int. Java is strongly typed, and there is no implicit type conversion like you might find in a scripting language.

你不能将 a 转换String为 an int。Java 是强类型的,并且没有您在脚本语言中可能会发现的隐式类型转换。

To convert a Stringto an int, use an explicit conversion, like Integer.parseInt(String).

要将 a 转换Stringint,请使用显式转换,例如Integer.parseInt(String)

All member variables and elements of arrays are initialized with a default value. For inttypes, the value is 0. For reference types (any subtype of Object), the default value is null. Local variables don't get a default value, but the compiler analyzes the code to ensure that a value is assigned before the variable is read. If not, the code will not compile.

数组的所有成员变量和元素都使用默认值进行初始化。对于int类型,该值为 0。对于引用类型( 的任何子类型Object),默认值为null。局部变量不会获得默认值,但编译器会分析代码以确保在读取变量之前已分配值。否则,代码将无法编译。

I think what you want is something like this:

我认为你想要的是这样的:

int[] n = new int[Integer.parseInt(s[0]);
for (int idx = 0; idx < n; ++idx)
  n[idx] = Integer.parseInt(s[idx + 1]);

回答by Anthony Forloney

If you initialize your variables or objects to nullprior to using them,

如果您null在使用变量或对象之前将它们初始化为

String myVar1 = null;
Person bobby = null;

You could comparing the variable or object to not null,

您可以将变量或对象与非空进行比较,

if (myVar != null) {
  // myVar has a value.
}

回答by Thomas L?tzer

You can check for null:

您可以检查null

int[] n;
for(String num: s){
    if(n == null) {
        n = new int[(int) num];
    }
    n[n.length] = (int) num;
}

Note that this can only happen if n is a class member. If it is a local variable, the compiler will not let you do anything with it without it being initialized.

请注意,只有当 n 是类成员时才会发生这种情况。如果它是一个局部变量,编译器不会让你在没有初始化的情况下对它做任何事情。

回答by Andrey

int[] n = null;
for(String num: s){
    if(n == null){
        n = new int[(int) num];
        continue;
    }
    n[n.length] = (int) num;
}

回答by Joachim Sauer

You can't check if a variable is initialized in your code, because by definition reading from a variable that mightnot have been initialized leads to a compile-time error.

您无法检查代码中是否初始化了变量,因为根据定义,从可能尚未初始化的变量中读取导致编译时错误。

You can initialize the variable to nulland check for that value ifyour variable is not a primitive type andnullis not a valid value after the initialization.

如果您的变量不是原始类型并且在初始化后不是有效值,您可以将变量初始化为null并检查该值。null

In the specific example the second code you showed would definitely be cleaner.

在特定示例中,您展示的第二个代码肯定会更清晰。

回答by Oliver Michels

You might want to take a look at the other datastructures in the collections framework.

您可能想查看集合框架中的其他数据结构。

-> http://java.sun.com/developer/onlineTraining/collections/Collection.html

-> http://java.sun.com/developer/onlineTraining/collections/Collection.html

ArrayList is a reasonable good alternative to arrays

ArrayList 是数组的合理替代品

回答by fastcodejava

Only thing you can do is check against null. If your code is within a method, it will not compile if you don't initialize. So if it compiles and run you know it is initialized to at least nulland then do the nullchecking.

你唯一能做的就是检查null。如果你的代码在一个方法中,如果你不初始化它就不会编译。因此,如果它编译并运行,您就知道它至少已初始化null,然后进行null检查。

回答by Jay

As others have noted, the closest thing to a "right way" to do this is to initialize the array to null.

正如其他人所指出的,最接近“正确方法”的方法是将数组初始化为 null。

On other points:

在其他方面:

"n[n.length]" will throw an "index out of bounds" exception. Arrays have elements ranging from 0 to length-1. In any case, I think what you intended to say in the first case was "n[0]" and in the second was "n[i]".

"n[n.length]" 会抛出一个 "index out of bounds" 异常。数组的元素范围从 0 到 length-1。无论如何,我认为您在第一种情况下打算说的是“n[0]”,而在第二种情况下是“n[i]”。

Storing the size of an array in the first element is probably a bad idea. It can be done for an int array, but it would be messy in a String array and it wouldn't work at all for a boolean array. Even in the int case, you're now mixing two very different things in the same data structure, which is likely to be confusing. If the array size is fixed, "length" holds the size anyway. If the array size is variable and you're thinking that you're going to create an array big enough and then store the amount you actually use, you are better off using ArrayList, which handles dynamic-size arrays cleanly.

将数组的大小存储在第一个元素中可能是一个坏主意。它可以用于 int 数组,但它在 String 数组中会很混乱,并且对于布尔数组根本不起作用。即使在 int 情况下,您现在也在同一数据结构中混合了两种截然不同的东西,这可能会令人困惑。如果数组大小是固定的,“长度”无论如何都会保持大小。如果数组大小是可变的,并且您认为要创建一个足够大的数组,然后存储实际使用的数量,则最好使用 ArrayList,它可以干净地处理动态大小的数组。

回答by Adam_G

I ran into this issue, checking if an inthas been initialized. In my program, it was possible that it was initialized to 0, so checking if (int i = 0)wouldn't do much good.

我遇到了这个问题,检查是否int已初始化。在我的程序中,它可能被初始化为0,因此检查if (int i = 0)不会有多大好处。

As a solution/work-around, I created a booleanvariable that is set when the intis initialized. Hope this helps.

作为解决方案/变通方法,我创建了一个booleanint初始化时设置的变量。希望这可以帮助。