如何在Java中查找数组中元素的数量?

4

我想知道如何在Java中查找普通数组中的元素数量。例如,如果我有一个大小为10的int数组,我只插入了5个元素。现在,我想检查我的数组中元素的数量?以下是更多澄清的代码。请帮忙。

public static void main(String[] args) {

        int [] intArray = new int[10];
        char [] charArray = new char[10];

        int count = 0;

        for(int i=0; i<=5; i++) {

            intArray[i] = 5;    
            charArray[i] = 'a';


        }


        for(int j=0; j<=intArray.length; j++) {
            if(intArray[j] != null) {
                count++;
            }
        }

        System.out.println("int Array element : "+ count);
    }

2
在原始循环中添加计数。 - Hayden
1
也许现在是学习列表的时候了。 - chancea
@Vid - 只是为了明确,您不想更改数组,只是想要返回类似于“10个元素中有5个为空”的内容,对吗? - Ascalonian
1
在Java中不存在“部分填充的数组”这种说法。整个数组都被填满了;只是有些元素可能仍然设置为默认值。 - Louis Wasserman
@Vid - 太好了!请看下面我的答案 :-) - Ascalonian
显示剩余4条评论
6个回答

8
代码有误。您声明了一个 int[] :它不能包含空值,因此该语句无法编译:
if(intArray[j] != null) {

如果您想存储许多项目,但不知道有多少个,应该使用一个集合(Collection),例如ArrayList

List<Integer> ints = new ArrayList<Integer>(); //Or new ArrayList<>(); - Java7

然后,您可以使用以下方式获取大小: ``` 然后,您可以使用以下方式获取大小: ```
ints.size();

现在,如果你真的想使用数组,那么你可以例如计算非零值的数量:

for(int j=0; j<=intArray.length; j++) {
  if(intArray[j] != 0) {
    count++;
  }
}

或者更好的是在Java 7中:

for(int i : intArray) {
  if(i!=0) {
    count++;
  }
}

Java 8中更加优秀:

Arrays.stream(intArray).filter(i -> i !=0).count();

3

查看Collection.frequency()。 这将计算特定对象(在本例中为null)出现在集合中的次数。

以下只是一个示例,以帮助您理解。

String[] array = new String[5];

array[0] = "This";
array[1] = null;
array[2] = "is";
array[3] = null;
array[4] = "a test";

int count = Collections.frequency(Arrays.asList(array), null);

System.out.println("String: " + count + " items out of " + array.length + " are null");

int[] iArray = new int[3];
iArray[0] = 0;
iArray[1] = 1;
iArray[2] = 2;

List<Integer> iList = new ArrayList<>();

for (int i : iArray) {
    iList.add(i);
}

int iCount = Collections.frequency(iList, 0);

System.out.println("Int: " + iCount + " items out of " + iArray.length + " are zero");

char[] cArray = new char[3];
cArray[0] = 'c';
cArray[1] = ' ';
cArray[2] = 'a';

List<Character> cList = new ArrayList<>();

for (char c : cArray) {
    cList.add(c);
}

int cCount = Collections.frequency(cList, ' ');

System.out.println("Char: " + cCount + " items out of " + cArray.length + " are ' '");

输出:

字符串:5个项目中有2个为空
整数:3个项目中有1个为零
字符:3个项目中有1个是空格


使用字符串数组而不是整数或字符。 - Vid
由于int和char是原始类型,您无法检查它们是否为“null”。您将如何检查它们? - Ascalonian
对于整型变量,它可以是0;对于字符型变量,它可以是空格。但是目前不起作用。 - Vid
@Vid - 我为你添加了int和char的示例代码。由于它们是原始类型,所以需要先将它们转换为List - Ascalonian

0

好的,我们可以使用计数来统计数组中非零元素的数量,代码如下:

public class SomeElementOfArrayUsingCount{

public static void main(String[] args){

     double total;//The sum of non-zero numbers in the Array.
     total=0;
     double average;//The average of non-zero numbers.
     int i;
     double count;//The number of non-zero numbers.
     count = 0;
     int[] list;
     list = new int[5];//make a container of 5.
     list[0]=2;
     list[1]=4;
     list[2]=4;
     list[3]=5;
     list[4]=2;

   for(i=0;i<list.length;i++){
       if(list[i]!=0){
           total = total + list[i];//Add element to the array
           count = count + 1;//and Count it
       }
   }

   if(count==0){
       System.out.println("There were no non-zero elements");
   }

   else {
       average = total/count;//Divide by number of items
       System.out.println("The average is " + average + " the total count is " + count);
   }
      } 
     }

0
你可以将第一个循环改为以下内容:
for(int i=0; i<=5; i++) {
     intArray[i] = 5;    
     charArray[i] = 'a';
     count++;
}

更好的方法是,不要使用数组,而是使用ArrayList。以下是ArrayList的工作示例。

ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<Character> charList = new ArrayList<Character>();
for (int i = 0; i < 5; i++){
    intList.add(5);
    charList.add('a');
}
System.out.println("int list element : " + intList.size());

ArrayList是动态的,.size()只会返回当前数组列表中项目的大小。


0
如果您想要实现自己的数组元素计数解决方案,您可以随时使用包含array的自己的包装类来实现。
public class classWithArray {
    private int[] arr;
    private int count;        

    public classWithArray(int arrLength) {
        arr = new int[5];
        count = 0;
    }

    public void add(int num) {
        arr[count] = num;
        count++;
    }        

    public int getCount() {
        return count;
    }

    public int getElement(int index) {
        return arr[index];
    }

    // Add other wrapper methods.

}

你可以使用泛型来创建一个Generic类型的array(我对于Java不是很了解),以使其适用于任何数据类型。

-3

sysout();

这将有助于您的进程,因为它将打印出您要查找的答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接