我想知道一个数组是否可以有一些空单元格和其他一些非空单元格。
例如,考虑大小为 3 的数组 arr:
arr[0] = null;
arr[1] = "hello";
arr[2] = null;
这可能吗?
我怎么可能得到第一个非空值?
我想知道一个数组是否可以有一些空单元格和其他一些非空单元格。
如果数据类型 extends Object
,那么可以。否则,如果它是原始数据类型,那么不,你不能。
例如:
Object[] arr = new Object[3];
arr[0] = null; // This is allowed.
int[] arr1 = new int[3];
arr1[0] = null; // This is NOT allowed.
我怎么可能得到第一个非空值?
要获得第一个非空值,请遍历数组(使用for
,for-each
循环,这是您的愿望),并继续循环直到当前元素为null
. 一旦你遇到一个非空元素,得到它并跳出循环。
我想知道一个数组是否可以有一些空单元格和其他一些非空单元格?
如果用空单元格表示包含的单元格,null
那么是的。当您创建对象数组时,它null
默认填充为 s,而在填充其他值时,它处于具有一些空值和一些非空值的状态。
我怎么可能得到第一个非空值?
您可以创建这样的方法
public static <T> T firstNonEmptyValue(T[] array){
for(T element : array){
if (element != null)
return element;// return first element that is not null
}
// if we are here it means that we iterated over all elements
// and didn't find non-null value so it is time to return null
return null;
}
用法
String[] arr = new String[] { null, "hello", null, "world", null };
System.out.println(firstNonEmptyValue(arr));//output: hello
System.out.println(firstNonEmptyValue(new String[42])); // output: null since array
// contains only nulls