java中如何计算数组中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4441099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you count the elements of an array in java
提问by El Fuser
Say i have the array
说我有数组
int theArray = new int[20];
The length of the array is 20 but the count is 0. How can i get the count?
数组的长度为 20,但计数为 0。如何获得计数?
采纳答案by Jon Skeet
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 distinctionbetween that array and one which has explicitlybeen 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. There's no concept of "the amount of the array currently in use".
Java 中的数组始终具有固定大小 - 通过length
字段访问。没有“当前使用的数组数量”的概念。
回答by Ram
int theArray[] = new int[20];
System.out.println(theArray.length);
回答by Petar Minchev
There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.
对此没有内置功能。这个计数是整个用户特定的。维护一个计数器或其他什么。
回答by Oded
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.
您不能做的是找出您填充的项目数量,除非在您自己的代码中对其进行跟踪。
回答by jjnguy
What I think you may want is an ArrayList<Integer>
instead of an array. This will allow you do to:
我认为您可能想要的是一个ArrayList<Integer>
而不是数组。这将允许您执行以下操作:
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.)
然后,您可以将内容添加到列表中,它会为您跟踪计数。(它也会根据需要增加后备存储的大小。)
回答by TartanLlama
Iterate through it and count the elements which aren't 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:each 循环等来整理,但这是 jist。
Either that, or keep a counter and whenever you add an element, increment it.
要么,要么保持一个计数器,每当你添加一个元素时,增加它。
回答by Edwin Buck
Java doesn't have the concept of a "count" of the used elements in an array.
Java 没有数组中使用的元素的“计数”的概念。
To get this, Java uses an 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).
为了实现这一点,Java 使用了一个ArrayList
. 在List
上每当JVM决定是不是足够大,其被调整(或有时当它太大了)阵列的基础上实现的。
To get the count, you use mylist.size()
to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20)
. To get rid of the extra capacity, you use mylist.trimToSize()
.
为了获得计数,您使用mylist.size()
来确保您使用的容量(底层数组支持)mylist.ensureCapacity(20)
。要摆脱额外的容量,您可以使用mylist.trimToSize()
.
回答by prgmast3r
You can use a for each loop and count the number of integer values that are significant. You could also use an ArrayList which will keep track of the couny for you. 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.
您可以为每个循环使用 a 并计算重要的整数值的数量。您还可以使用 ArrayList 来为您跟踪县。每次从列表中添加或删除对象时,它都会自动更新计数。调用 size() 方法将为您提供当前的元素数。
回答by khachik
- Your code won't compile, it should be
int [] theArray = new int[20];
; - You can get the array length as
theArray.length
; - For primitive types, the array will be initialized with the default values (0 for int).
You can make it
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; }
- 你的代码不会编译,它应该是
int [] theArray = new int[20];
; - 你可以得到数组长度为
theArray.length
; - 对于原始类型,数组将使用默认值(0 表示 int)进行初始化。
您可以创建它
Integer [] theArray = new Integer[20];
,然后像此代码那样计算初始化成员: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.
请注意,这个答案不是关于您为什么需要这个以及做您想做的事情的最佳方法是什么。
回答by adimitri
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;