public class Yuri{ private String name = "Yuri"; private ArrayList<String> words = new ArrayList<>(); public void setName(String name) { this.name = name; } public void addWord(String word){ this.words.add(word); } @Override protected Yuri clone(){ try{ return (Yuri) super.clone(); }catch (CloneNotSupportedException e){ return null; } } @Override public String toString() { return "Yuri{" + "name=‘" + name + ‘\‘‘ + ", words=" + words.toString() + ‘}‘; } }
如上,重写了clone()方法。在执行如下代码时:
Yuri yuri = new Yuri(); yuri.setName("Yuri"); yuri.addWord("My name is Yuri"); yuri.addWord("You mind is clear"); Yuri yuri_copyer = yuri.clone(); yuri.setName("Yuri‘s copyer");
/** * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { try { ArrayList<?> v = (ArrayList<?>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn‘t happen, since we are Cloneable throw new InternalError(e); } }