Well, I have a have a primitive array of objects, and because I can't remove them from the array, I instead change the object's position in the array to null. However, if I want to iterate over each object in the array, in the following way:
for (Derp derp : derps){
derp.herp++;
}
Do I have to do something like this?
for (Derp derp : derps){
if (derp != null){
derp.herp++;
}
}
Or would it be fine the first way I had it? Will the for loop 'know' that it only has to iterate over the Derp objects, and not the null objects, because I've declared it as a Derp object? Or perhaps it just treats it as a Derp object because I've said it would be, and it would cause an error when it tries to iterate over a non-Derp object? Or is null still a Derp object, just one that is null? Which is it, and what code can I use?
Alternatively, how can I remove an object from a primitive array and not leave a null object and actually shorten the length of the primitive array?
This is better.
for (Derp derp : derps){
if (derp != null){
derp.herp++;
}
}
The first one throws nullpointer exception.if any value is null
how can I remove an object from a primitive array and not leave a null object.
Once memory allocated to that element in array, least you can do is making it null
.
actually shorten the length of the primitive array?
No. It is fixed while declaring it self.After the deceleration you cannot change the length.
Arrays died long back. Your best bet is List
which have benefites of
Positional access
— manipulates elements based on their numerical
position in the list. This includes methods such as get, set, add,
addAll, and remove.Search
— searches for a specified object in the list and returns its
numerical position. Search methods include indexOf and lastIndexOf.Iteration
— extends Iterator semantics to take advantage of the
list's sequential nature. The listIterator methods provide this
behavior.Range-view
— The sublist method performs arbitrary range operations
on the list.Null is a valid list item so you will need to check for it.
You can not simply remove an element from a primitive Array. You can use a more advanced structure such as ArrayList where elements can be removed. The following two examples are one-liners to remove all NULL values from a List.
list.removeAll(Collections.singleton(null));
or
list.removeAll(Arrays.asList(new Object[]{null}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With