-1

I get an error on the line where I set this.pastMoves = pastMoves.clone()

I think that you can clone an ArrayList but maybe not a List? I'm not too sure but it does not want to clone.

This class is a part of a program to find the shortest path a knight can make on a chessboard from one location to another. I need to spawn new knights off of older moves and pass the old moves on as well as add a new one. If I do not clone the list then all separate moves will add on to one large list, but I need different paths to save separately.

import java.util.List;

/*
 * This class is for the knight which holds information
 * on its previous moves and its current move
 */
public class Knight {
        
    private List<int[]> pastMoves;
    private int[] currentLocation;
    
    public Knight(List<int[]> pastMoves, int[] currentMove) {
        this.pastMoves = pastMoves.clone();
        pastMoves.add(currentMove);
        currentLocation = currentMove;
    }
    
    public List<int[]> getPastMoves(){
        return pastMoves;
    }
    
    public int[] getCurrentLocation() {
        return currentLocation;
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

4

It is certainly possible to copy a List, but clone() is, in general, an ill-advised language feature you should never use.

To do a shallow copy of a List, just write e.g. new ArrayList<>(list), which uses the ArrayList copy constructor.

To do a deep copy of a List, you should be manually copying each element over to a new List, probably an ArrayList, using the appropriate means of deep copying that element type.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413