可以在Java中使用`.clone()`方法克隆一个List吗?

huangapple go评论62阅读模式
英文:

Is it possible to .clone() a List in Java?

问题

在我设置this.pastMoves = pastMoves.clone()的那行代码上出现了一个错误。

我认为你可以克隆一个ArrayList,但也许不能克隆一个List?我不太确定,但它似乎无法克隆。

这个类是程序的一部分,用于找到国际象棋棋盘上一个位置到另一个位置的骑士可以走的最短路径。我需要在旧的移动基础上产生新的骑士,并将旧的移动传递下去,同时添加一个新的移动。如果我不克隆该列表,那么所有单独的移动都会添加到一个大列表中,但我需要将不同的路径分开保存。

import java.util.List;

/*
 * 此类用于骑士,保存其先前的移动信息和当前的移动
 */
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;
	}
}
英文:

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&lt;int[]&gt; pastMoves;
	private int[] currentLocation;
	
	public Knight(List&lt;int[]&gt; pastMoves, int[] currentMove) {
		this.pastMoves = pastMoves.clone();
		pastMoves.add(currentMove);
		currentLocation = currentMove;
	}
	
	public List&lt;int[]&gt; getPastMoves(){
		return pastMoves;
	}
	
	public int[] getCurrentLocation() {
		return currentLocation;
	}
}

答案1

得分: 4

可以肯定地复制一个List,但clone()通常是一个不建议使用的语言特性,你不应该使用它。

要做一个List的浅拷贝,只需编写例如 new ArrayList&lt;&gt;(list),它使用ArrayList的拷贝构造函数。

要做一个List的深拷贝,你应该手动将每个元素复制到一个新的List,可能是一个ArrayList,并使用适当的深拷贝该元素类型的方法。

英文:

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&lt;&gt;(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.

huangapple
  • 本文由 发表于 2020年10月23日 02:17:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64488270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定