Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a for loop in Java, do I have to specify not null?

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?

like image 667
LaneWalker Avatar asked Oct 29 '13 06:10

LaneWalker


Video Answer


2 Answers

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.
like image 91
Suresh Atta Avatar answered Sep 25 '22 10:09

Suresh Atta


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})); 
like image 27
Samuel O'Malley Avatar answered Sep 22 '22 10:09

Samuel O'Malley