[英]java get the number of array values
我已经有了以下代码
public class Qn3
{
static BigDecimal[] accbal= new BigDecimal[20];
private static Integer[] accnums = new Integer[5];
public static void main(String[] args)
{
int count;
accnums = {1,2} //i cant add this line of code as well, what is wrong?
while(accnums.length < 5)
{
count = accnums.number_of_filled_up_indexes
//this is not actual code i know
//do this as the number of values in the array are less than 5
break;
}
//do this as number of values in the array are more than 5
}
}
我必须使用这个代码没有改变这是一个要求,所以请不要建议使用arraylist等(我知道其他数组类型和方法)
问题是因为我已经声明accnums
必须只包含5个值,这是预定义的。
我正在尝试检查那些非null并且是否都为null。 要做到这一点,我试过这个,但这给了我5 p(预定义的整数数组值不是我想要的)。
public static void main(String[] args)
{
int count = 0;
accnums = new Integer[] {1,2,null,null,null};
for (int index = 0; index < accnums.length; index++)
{
if(accnums[index] != null)
{
count++;
}
}
System.out.println("You have used " + count + " slots);
}
试试这个...
accnums[0] = new Integer(1);
accnums[1] = new Integer(2);
如果在声明和初始化时间和数组期间完成,则以下两者都将起作用。
Integer[] arr = new Integer[]{1,2,3};
Integer[] arr = {1,2,3}
但是当你只是将数组声明为
Integer[] arr = new Integer[3]; // Still array holds no Object Reference Variable
然后以这种方式初始化它......
arr = new Integer{1,2,3,}; // At this time it hold the ORV
无论是在类还是方法范围内使用,数组总是被初始化 ,因此对于int数组,所有值都将默认设置为0,而对于Integer
,它将为null
,因为它是一个Wrapper object
。
例如:
Integer[] arr = new Integer[5];
arr[0] = 1;
arr[1] = 2;
System.out.println(arr.length);
for (Integer i : arr){
if (i!=null){
count++;
}
}
System.out.println("Total Index with Non Null Count :"+count);
}
accnums[0] = 1;
accnums[1] = 2;
final int count = accnums.length
- Collections.frequency(Arrays.asList(accnums), null);
System.out.println("You have used " + count + " slots");
或者,如果你真的必须手动做...
int count;
for (final Integer val : accnums) {
if (val != null) {
++count;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.