java获取数组值的数量

java获取数组值的数量,java,arrays,Java,Arrays,我已经有了下面的代码 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

我已经有了下面的代码

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
    }
}
公共类Qn3
{
静态BigDecimal[]accbal=新的BigDecimal[20];
私有静态整数[]accnums=新整数[5];
公共静态void main(字符串[]args)
{
整数计数;
accnums={1,2}//我也不能添加这行代码,怎么了?
while(accnums.length<5)
{
计数=帐户数。填充索引数
//这不是我知道的实际代码
//这样做是因为数组中的值数小于5
打破
}
//由于数组中的值数大于5,请执行此操作
}
}
我必须使用此代码。没有更改这是一项要求,因此请不要建议使用arraylist等(我知道其他数组类型和方法)

问题在于,正如我已经声明的那样,
accnums
必须只包含5个预定义的值

我正在尝试执行一项检查,检查是否有不为null的项,以及是否所有项都为null。为了做到这一点,我尝试了这个,但这是给我5 p(预定义的整数数组值不是我想要的)

试试这个

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,对于
整数
,它将被设置为
null
,作为它的
包装对象

例如:

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

公共静态void main(字符串[]args)
{
整数计数=0;
accnums=新整数[]{1,2,null,null,null};
对于(int index=0;index
或者,如果你真的必须手动操作

int count;
for (final Integer val : accnums) {
  if (val != null) {
    ++count;
  }
}

是的,可以将值添加到整数数组中。但我的主要问题仍然是检查整数数组中填充了多少。对不起,误解了这个问题。请参阅程序员的答案-只需使用for循环,并将计数保留在一个变量中,您可以为每个非空索引递增。最后的计数将是the非空值的总数。
accnums.length-Collections.frequency(Arrays.asList(accnums),null)
PS
accnums
应为
新整数[5]{1,2,null,null,null}
@veer首先,我们不允许
列表
s:P,其次-干杯没问题,老兄!我想我们可以使用
数组。asList
,只是不能取代
帐户的类型
:-)@veer这只是我对需求的理解,现实可能不同;)
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;
  }
}