简体   繁体   English

java中如何计算数组的元素

[英]How do you count the elements of an array in java

Say i have the array说我有数组

int theArray = new int[20];

What do you mean by "the count"? “伯爵”是什么意思? The number of elements with a non-zero value? 具有非零值的元素数量? You'd just have to count them. 你只需要数数吧。

There's no distinction between that array and one which has explicitly been set with zero values. 该数组与明确设置为零值的数组之间没有区别 For example, these arrays are indistinguishable: 例如,这些数组是无法区分的:

int[] x = { 0, 0, 0 };
int[] y = new int[3];

Arrays in Java always have a fixed size - accessed via the length field. Java中的数组总是有固定的大小 - 通过length字段访问。 There's no concept of "the amount of the array currently in use". 没有“当前使用的阵列数量”的概念。

Iterate through it and count the elements which aren't null: 迭代它并计算非null的元素:

int counter = 0;
for (int i = 0; i < theArray.length; i ++)
    if (theArray[i] != null)
        counter ++;

This can be neatened up by using for:each loops and suchlike, but this is the jist. 这可以通过使用for来实现:每个循环等等,但这是jist。

Either that, or keep a counter and whenever you add an element, increment it. 无论是那个,还是保留一个计数器,每当你添加一个元素时,都要增加它。

What I think you may want is an ArrayList<Integer> instead of an array. 我认为你可能想要的是一个ArrayList<Integer>而不是一个数组。 This will allow you do to: 这将允许您:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0 . 输出将为0

Then, you can add things to the list, and it will keep track of the count for you. 然后,您可以将内容添加到列表中,它将跟踪您的计数。 (It will also grow the size of the backing storage as you need as well.) (它也会根据您的需要增加后备存储的大小。)

Java doesn't have the concept of a "count" of the used elements in an array. Java没有对数组中使用的元素进行“计数”的概念。

To get this, Java uses an ArrayList . 为此,Java使用ArrayList The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big). List是在一个数组之上实现的,只要JVM决定它不够大(或者有时候它太大),它就会被调整大小。

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20) . 要获得计数,可以使用mylist.size()来确保使用mylist.ensureCapacity(20)的容量(基础数组后备mylist.ensureCapacity(20) To get rid of the extra capacity, you use mylist.trimToSize() . 要消除额外的容量,可以使用mylist.trimToSize()

There is no built-in functionality for this. 没有内置功能。 This count is in its whole user-specific. 此计数是整个用户特定的。 Maintain a counter or whatever. 维护柜台或其他什么。

  1. Your code won't compile, it should be int [] theArray = new int[20]; 你的代码不会编译,应该是int [] theArray = new int[20]; ; ;
  2. You can get the array length as theArray.length ; 你可以得到数组长度为theArray.length ;
  3. For primitive types, the array will be initialized with the default values (0 for int). 对于基本类型,将使用默认值(对于int为0)初始化数组。
  4. You can make it Integer [] theArray = new Integer[20]; 你可以使它成为Integer [] theArray = new Integer[20]; and then count initialized members as this code does: 然后计算初始化成员,如下代码所示:

     public int count(Object [] array) { int c = 0; for(Object el: array) { if(el != null) c++; } return c; } 

Please note that this answer isn't about why you may need this and what is the best way to do what you want. 请注意,这个答案不是为什么你可能需要这个,以及什么是你想要的最佳方式。

When defining an array, you are setting aside a block of memory to hold all the items you want to have in the array. 在定义数组时,您要预留一块内存来保存您想要在数组中拥有的所有项目。

This will have a default value, depending on the type of the array member types. 这将具有默认值,具体取决于数组成员类型的类型。

What you can't do is find out the number of items that you have populated, except for tracking it in your own code. 你不能做的是找出你填充的项目数,除了在你自己的代码中跟踪它。

You can use a for each loop and count the number of integer values that are significant. 您可以为每个循环使用a并计算重要的整数值的数量。 You could also use an ArrayList which will keep track of the couny for you. 您还可以使用ArrayList来跟踪您的状态。 Everytime you add or remove objects from the list it will automatically update the count. 每次从列表中添加或删除对象时,它都会自动更新计数。 Calling the size() method will give you the current number of elements. 调用size()方法将为您提供当前的元素数。

If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable. 如果您希望有一个阵列,您将不会分配所有元素,您将必须自己进行簿记,以确保通过其他变量放置了多少元素。 If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList 如果你想避免这样做同时获得一个可以在初始实例化后增加容量的“数组”,你可以创建一个ArrayList

ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5

Don't forget to import it at the top of the file: 不要忘记在文件顶部导入它:

import java.util.ArrayList;

If you assume that 0 is not a valid item in the array then the following code should work: 如果您假设0不是数组中的有效项,则以下代码应该起作用:

   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array) 
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }

You can declare an array of booleans with the same length of your array: 您可以声明一个与数组长度相同的布尔数组:

true: is used true:使用
false: is not used false:未使用

and change the value of the same cell number to true. 并将相同单元格的值更改为true。 Then you can count how many cells are used by using a for loop. 然后,您可以使用for循环计算使用了多少个单元格。

You could also make it an Integer array.您也可以将其设为整数数组。 That way each item will be null.这样每个项目都将为空。 Then just count the number of non-null values.然后只计算非空值的数量。 This still allows you to add ints, like you could before since Java does autoboxing and unboxing of primitives and their wrappers.这仍然允许您添加整数,就像以前一样,因为 Java 对原语及其包装器进行自动装箱和拆箱。

Integer[] numbers = new Integer[30];

int count = 0;
for (Integer num : numbers)
    if (num != null) count++;

System.out.println(count);
int theArray[] = new int[20];
System.out.println(theArray.length);

Isn't it just: System.out.println(Array.length); 不仅仅是: System.out.println(Array.length); ? Because this is what it seems like you are looking for. 因为这就像你正在寻找的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM