How to order the way in which objects are rendered?

     Let's say for example I have an Int called "Layer" in all the objects that I have. Multiple objects can have this Int set to the same amount , and the layer int can go as high as 999. I want all the objects with the Layer Int equal to 1 drawn first and so on. I know I can easily do this if I had 3 layers with just 3 if statements, but how would I handle numbers such as 999 different "Layers?" ?

Maintain a list of your objects and use a Comparator to sort them by layer. Then iterate through the list.

That’s probably one of the best ways.

A less ideal way would be to use one for loop to go between layers, and check if entity.getLayer() == i (loop variable). But I suggest going with the way above (just make sure you’re only sorting them occasionally, and not every single frame).

To go over CopyableCougar4’s method (which is preferred), the Comparator interface has a method called compare(Object first, Object second). It returns either -1, 0, or 1. It returns -1 if the first object is “less than” the second. It returns 0 if they’re equal, and returns 1 if the first object is “greater than” the second object. You could return it based on layer. As Ashedragon said, don’t sort every frame, but maybe you should sort when an entity is added (not removed because that shouldn’t have an effect on the sorted array/list).

Sort every frame. Optimize only when profiling shows sorting takes longer than, say, 1ms.

Yeah should be fine in most cases.

Just to build on what Riven and Cero said.

You sort by layer, which means sorting each frame will take literally no time at all.

You may have a list of layers that contain a list of items, spanning many thousands. The internal array is never sorted, only the layer list is sorted.

So think of a layer as a data structure for render able objects, so to say.

Alright, thank you all! ;D