java获取数组值的数量

时间:2012-08-27 02:56:25

标签: 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 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(预定义的整数数组值不是我想要的)。

3 个答案:

答案 0 :(得分:4)

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

}

答案 1 :(得分:2)

试试这个......

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,它将为{{ 1}},因为它是null

<强>例如

Wrapper object

}

答案 2 :(得分:0)

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