Step-by-step comments included below (with a couple of minor modifications in the code):
This can be slightly improved upon, with:
// create a new segment Snake s = new Snake(); // create temporary segment array of equal length Snake[] oldSnake = new Snake[snakeBody.length]; // copy data from original array to temporary array for(int i=0; i<snakeBody.length; i++) oldSnake[i] = snakeBody[i]; // re-create original array allowing one more element snakeBody = new Snake[snakeBody.length+1]; // copy data from temporary array to re-created original array for(int i=0; i<oldSnake.length; i++) snakeBody[i] = oldSnake[i]; // add the new segment to the array snakeBody[snakeBody.length-1] = s; // add the new segment into the world addObject(snakeBody[s, previousLocationX, previousLocationY);
Snake[] oldSnake = new Snake[snakeBody.length]; System.arraycopy(snakeBody, 0, oldSnake, 0, snakeBody.length); snakeBody = new Snake[oldSnake.length+1]; System.arraycopy(oldSnake, 0, snakeBody, 0, oldSnake.length); snakeBody[snakeBody.length-1] = new Snake(); addObject(snakeBody[snakeBody.length-1], previousLocationX, previousLocationY);