假设我有一个数组
int theArray = new int[20];
数组的长度为20,但计数为0。我该如何获得计数?
假设我有一个数组
int theArray = new int[20];
数组的长度为20,但计数为0。我该如何获得计数?
"计数"的意思是什么?指具有非零值的元素数量吗?您只需对它们进行计数即可。
这个数组和明确设置为零值的数组之间没有区别。例如,这些数组是无法区分的:
int[] x = { 0, 0, 0 };
int[] y = new int[3];
Java中的数组始终具有固定的大小-通过length
字段访问。没有“当前正在使用的数组数量”的概念。
遍历它并计算其中不为null元素的数量:
int counter = 0;
for (int i = 0; i < theArray.length; i ++)
if (theArray[i] != null)
counter ++;
可以使用for:each循环等方式使其更加简洁,但这就是要点。
否则,保持一个计数器,每次添加元素时增加它。
我认为你可能需要使用ArrayList<Integer>
而不是数组。这将允许你做到以下几点:
ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());
输出将为0
。int [] theArray = new int[20];
;theArray.length
;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;
}
Java中没有数组中已使用元素的“计数”概念。
为了解决这个问题,Java使用了一个ArrayList
。该List
是在数组上实现的,当JVM认为它不够大(或者有时太大)时,该数组会被调整大小。
要获取计数,您可以使用mylist.size()
来确保容量(支持底层数组),您可以使用mylist.ensureCapacity(20)
。要摆脱额外的容量,您可以使用mylist.trimToSize()
。
这个功能没有内置。这个计数是针对整个用户的。需要维护一个计数器或类似的东西。
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
import java.util.ArrayList;
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;
}
你可以声明一个与你的数组长度相同的布尔数组:
true:已使用
false:未使用
然后将相同单元格编号的值更改为true。接下来,你可以使用for循环计算有多少单元格已被使用。
在定义数组时,您正在设置一块内存来容纳您想要放入数组中的所有项目。
这将具有默认值,取决于数组成员类型的类型。
您无法找出已填充的项目数量,除非在自己的代码中进行跟踪。