ArrayList list = new ArrayList() ;
list.add (o1) ;
list.add(o2) ;
ArrayList newList = (ArrayList) list.clone() ;
//This is a shallow copy so
list != newList,
but ,
list.get(0) == newList.get(0) and
list.get(1) == newList.get(1)
If a deep copy is done, then
list!=newList
list.get(0) != newList.get(0) and
list.get(1) != newList.get(1).. however list.get(0).equals(newList.get(0)) returns true.
romanoTC:
public void setMyList(List argument)
{
// The usage of array list depends on each implementation
// If it fits yours, use it
this.myList = new ArrayList(argument);
}
this.myList = new ArrayList(argument);
----注意这里不要有两步,会很麻烦。
List list = new ArrayList()
list.add(..)
为什么用 浅拷贝?
Not always, sometimes.
When you just set reference, user can still change it's state, like adding or removing items, from outside of the class.
When you make copy, it's your very own collection. It will not change in any way unless you change it explicitly.
list.add (o1) ;
list.add(o2) ;
ArrayList newList = (ArrayList) list.clone() ;
//This is a shallow copy so
list != newList,
but ,
list.get(0) == newList.get(0) and
list.get(1) == newList.get(1)
If a deep copy is done, then
list!=newList
list.get(0) != newList.get(0) and
list.get(1) != newList.get(1).. however list.get(0).equals(newList.get(0)) returns true.
romanoTC:
public void setMyList(List argument)
{
// The usage of array list depends on each implementation
// If it fits yours, use it
this.myList = new ArrayList(argument);
}
this.myList = new ArrayList(argument);
----注意这里不要有两步,会很麻烦。
List list = new ArrayList()
list.add(..)
为什么用 浅拷贝?
Not always, sometimes.
When you just set reference, user can still change it's state, like adding or removing items, from outside of the class.
When you make copy, it's your very own collection. It will not change in any way unless you change it explicitly.