Return position of an arrangement, best practice

0

I have come across two ways to return a position in an arrangement, in an autoincremental function and I wanted to know which one would be considered better and why

1.-

public Object returnObject()
{
    objectIndex++;
    return objeto[objectIndex-1];
}

2 .-

public Object returnObject()
{
     Object objetoNuevo = objeto[objectIndex]
     objectIndex++;
     return objetoNuevo ;
}

The first option I like because it does not create a new instance of the object, it uses less lines, but it has a strange way of handling the index,

The second option seems simpler, although it uses a more code line and generates a new instance of the object, which does not seem to me at all a good practice either.

in cases like this one should resort to the efficiency of the code or the simplicity of it?

    
asked by Mike 13.04.2018 в 18:20
source

1 answer

0

From my point of view neither seems good , I explain why:

  • The possible overflow of the array of objects is ignored. Once the objectIndex has been increased, it must be taken into account if we have passed the capacity of the array.
  • In neither of the two is a new instance of the objects of the array. Object objectNew = object [objectIndex] creates a new reference but not a new instance. To create a new instance you should resort to the concept deepcopy (see this How do you make a deep copy of an object in Java? )
  • Greetings

    David

        
    answered by 27.04.2018 в 17:54