How to cut the Java of each loop in half?
•
Java
I'm working a lot for each loop in Java I'm using them to "draw" every class of my object, but it requires a lot of memory, so I want to reduce it by half. Is there a way for each loop instead of a complete list?
for(Tile tile: tiles){ tile.draw(); }
I want:
for(Tile tile: (half of)tiles){ tile.draw(); }
Is it possible or do I just need to get the length of the tile and break the cycle when it reaches the number?
Solution
Now that you have clarified that you have an ArrayList, you can use the sublist function to get the view of the first half of the list
for(Tile tile: tiles.subList(0,tiles.size()/2){ tile.draw(); }
This uses foreach loops and is very concise and readable code
Because the sublist is only a view of the original list, there is no penalty to copy to the new list
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码