问题
I am doing gift (String-type) storage, using arrays, with the maximum 500 million. I want to get the number of used elements in an array like how many gifts are currently in stock, (I.E. I stored 253538 gifts, but I don't know that. Is there a command in Java that can know that there is only 253538 Slots in the array that contain an element). But I don't know how to. Here's the snippet of code I want to use:
static String[] Gifts = new String[500000000];
static int i = 0;
String command, Gift;
while (true) {
//Gift Array Console
String command = scan.next();
if (command == "addgift") {
String Gift = scan.next();
Gifts[i] = Gift;
i++;
}
}
回答1:
You can iterate through the array and count the initialized array elements.
int counter = 0;
for (int i = 0; i < arrayName.length; i ++)
if (arrayName[i] != null)
counter ++;
Also it would be even better if you used ArrayList<String>
so you could use size()
ArrayList<String> arrayName = new ArrayList<String>(20);
System.out.println(arrayName.size());
It will print 0, as there are no elements added to the ArrayList.
回答2:
You can use Arrays.stream to iterate over this array of strings, then use filter to select nonNull elements and count them:
String[] arr = {"aaa", null, "bbb", null, "ccc", null};
long count = Arrays.stream(arr).filter(Objects::nonNull).count();
System.out.println(count); // 3
Or if you want to find the index of the first null
element to insert some value there:
int index = IntStream.range(0, arr.length)
.filter(i -> arr[i] == null)
.findFirst()
.getAsInt();
arr[index] = "ddd";
System.out.println(index); // 1
System.out.println(Arrays.toString(arr));
// [aaa, ddd, bbb, null, ccc, null]
See also: How to find duplicate elements in array in effective way?
来源:https://stackoverflow.com/questions/65328677/how-to-get-elements-of-an-array-that-is-not-null