簡體   English   中英

java獲取數組值的數量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM