In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the use of clone () and Cloneable interface in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Clone () and Cloneable interface
Clone is, as its name implies, cloning, that is, copying an equivalent object but with a different reference address.
We know that if we get the address of an object, we can modify it as long as we provide the corresponding method, but if we want to get the object to modify it, but also want to retain the original properties of the object, we can use clone (), which will copy an object with the same content and have a different memory address.
The Cloneable interface is the interface we must implement if we want to use clone (), or an exception will be thrown.
Public class Bean implements Cloneable {private String a; public Bean (String a) {this.a = a;} public String getA () {return a;} @ Override protected Object clone () throws CloneNotSupportedException {return super.clone ();} @ Override public boolean equals (Object o) {if (o instanceof Bean) {Bean bean = (Bean) o Return bean.getA () .equals (a);} return false;}}
There are no methods defined for us in the Cloneable interface
Here you need to override the clone () method
Protected native Object clone () throws CloneNotSupportedException;protected Object clone () throws CloneNotSupportedException {if (! (this instanceof Cloneable)) {throw new CloneNotSupportedException ("Class" + getClass (). GetName () + "doesn't implement Cloneable");} return internalClone ();}
It is the native method in the Object class, which is protected and can be written as public as needed. You can see that a CloneNotSupportedException exception will be thrown if the Cloneable interface is not implemented.
Test it
Try {Bean a = new Bean ("lzy"); Bean b = a; Bean c = (Bean) a.clone (); Log.i (TAG, "onCreate:" + (a = = b)); / / true Log.i (TAG, "onCreate:" + (a.equals (b) / / true Log.i (TAG, "onCreate:" + (a = = c)); / / false Log.i (TAG, "onCreate:" + (a.equals (c); / / true} catch (CloneNotSupportedException e) {e.printStackTrace ();}
You can see that the address of the cloned class is different, but the content is the same.
Let's modify it and add a member variable ChildBean to Bean
Public class ChildBean implements Cloneable {private String c; public String getC () {return c;} public ChildBean (String c) {this.c = c;} @ Override public Object clone () throws CloneNotSupportedException {return super.clone ();} @ Override public boolean equals (Object o) {if (o instanceof ChildBean) {ChildBean bean = (ChildBean) o Return bean.getC () .equals (c);} return false;}} public class Bean implements Cloneable {private String a; private ChildBean childBean; public Bean (String a, ChildBean childBean) {this.a = a; this.childBean = childBean;} public String getA () {return a;} public ChildBean getChildBean () {return childBean @ Override public Object clone () throws CloneNotSupportedException {return super.clone ();} @ Override public boolean equals (Object o) {if (o instanceof Bean) {Bean bean = (Bean) o; return bean.getA () .equals (a);} return false;}} Bean a = new Bean ("lzy", new ChildBean ("child")) Bean b = a; Bean c = (Bean) a.clone (); Log.i (TAG, "onCreate:" + (a.getChildBean () = = b.getChildBean (); / / true Log.i (TAG, "onCreate:" + (a.getChildBean (). Equals (b.getChildBean () / / true Log.i (TAG, "onCreate:" + (a.getChildBean () = = c.getChildBean (); / / true Log.i (TAG, "onCreate:" + (a.getChildBean (). Equals (c.getChildBean (); / / true
The test found that there is a result that is not what we expected, which means that ChildBean is not really cloned, but its memory address is cloned, resulting in two having the same memory address, that is, shallow cloning. What we need at this time is deep cloning, which needs to be modified as follows to rewrite the clone () method.
@ Override public Object clone () throws CloneNotSupportedException {Bean bean = (Bean) super.clone (); bean.childBean = (ChildBean) bean.childBean.clone (); return bean;}
But if there are many layers of classes, each layer needs to be rewritten, which is troublesome. So we can use the following tool class to implement
Public class BeanUtil {public static T cloneTo (T src) throws RuntimeException {ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream (); ObjectOutputStream out = null; ObjectInputStream in = null; T dist = null; try {out = new ObjectOutputStream (memoryBuffer); out.writeObject (src); out.flush (); in = new ObjectInputStream (new ByteArrayInputStream (memoryBuffer.toByteArray () Dist = (T) in.readObject ();} catch (Exception e) {throw new RuntimeException (e);} finally {if (out! = null) try {out.close (); out = null } catch (IOException e) {throw new RuntimeException (e);} if (in! = null) try {in.close (); in = null;} catch (IOException e) {throw new RuntimeException (e) } return dist;}} Bean a = new Bean ("lzy", new ChildBean ("child")); Bean b = BeanUtil.cloneTo (a); Log.i (TAG, "onCreate:" + (a.getChildBean () = = b.getChildBean (); / / false Log.i (TAG, "onCreate:" + (a.getChildBean (). Equals (b.getChildBean () / / true
This makes it easy to get the desired results, but remember that every class has to implement the Serializable interface.
The purpose of the summary 1.Cloneable for Cloneable and clone ()
Cloneable, like Serializable, is a tagged interface with no internal methods and properties. Implements Cloneable means that the object can be cloned and can use the Object.clone () method. If a class without implements Cloneable calls the Object.clone () method, a CloneNotSupportedException is thrown.
two。 Classification of clones
(1) shallow clone, shallow copy means that when copying an object, it only copies the object itself and the basic variables in the object, but not the object pointed to by the reference contained in the object.
(2) Deep cloning (deep clone), deep copy copies not only the object itself, but also all objects pointed to by the references contained in the object.
As an example, object A1 contains a reference to B1, and B1 contains a reference to C1. A shallow copy of A1 shows that A2 still contains a reference to B1 and B1 still contains a reference to C1. The deep copy is the recursion of the shallow copy, and the deep copy A1 gets the A2 sheet which contains the reference to B2 (the copy of B1) and B2 contains the reference to C2 (the copy of C1).
3. Examples of cloning
There are actually two steps for an object to be cloned:
1. Let the class implement the java.lang.Cloneable interface
two。 Override (override) the clone () method of the Object class.
Public class Wife implements Cloneable {private int id; private String name; public int getId () {return id;} public void setId (int id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name } public Wife (int id,String name) {this.id = id; this.name = name;} @ Override public int hashCode () {/ / myeclipse automatically generated final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name = = null)? 0: name.hashCode ()) Return result;} @ Override public boolean equals (Object obj) {/ / if automatically generated by myeclipse (this = = obj) return true; if (obj = = null) return false; if (getClass ()! = obj.getClass ()) return false; Wife other = (Wife) obj If (id! = other.id) return false; if (name = = null) {if (other.name! = null) return false;} else if (! name.equals (other.name)) return false; return true } @ Override public Object clone () throws CloneNotSupportedException {return super.clone ();} / * @ param args * @ throws CloneNotSupportedException * / public static void main (String [] args) throws CloneNotSupportedException {Wife wife = new Wife (1, "wang"); Wife wife2 = null; wife2 = (Wife) wife.clone () System.out.println ("class same=" + (wife.getClass () = = wife2.getClass (); / / true System.out.println ("object same=" + (wife==wife2)); / / false System.out.println ("object equals=" + (wife.equals (wife2); / / true}} 4. An example of shallow cloning: public class Husband implements Cloneable {private int id; private Wife wife; public Wife getWife () {return wife;} public void setWife (Wife wife) {this.wife = wife;} public int getId () {return id;} public void setId (int id) {this.id = id } public Husband (int id) {this.id = id;} @ Override public int hashCode () {/ / myeclipse automatically generated final int prime = 31; int result = 1; result = prime * result + id; return result;} @ Override protected Object clone () throws CloneNotSupportedException {return super.clone () } @ Override public boolean equals (Object obj) {/ / if automatically generated by myeclipse (this = = obj) return true; if (obj = = null) return false; if (getClass ()! = obj.getClass ()) return false; Husband other = (Husband) obj If (id! = other.id) return false; return true;} / * * @ param args * @ throws CloneNotSupportedException * / public static void main (String [] args) throws CloneNotSupportedException {Wife wife = new Wife (1, "jin"); Husband husband = new Husband (1); Husband husband2 = null Husband.setWife (wife); husband2 = (Husband) husband.clone (); System.out.println ("husband class same=" + (husband.getClass () = = husband2.getClass (); / / true System.out.println ("husband object same=" + (husband==husband2)); / / false System.out.println ("husband object equals=" + (husband.equals (husband) / / true System.out.println ("wife class same=" + (husband.getWife (). GetClass () = = husband2.getWife (). GetClass ()); / true System.out.println ("wife object same=" + (husband.getWife () = = husband2.getWife (); / / true System.out.println ("wife object equals=" + (husband.getWife (). Equals (husband.getWife (); / / true}} 5. Examples of deep cloning
If you want to make a deep clone, you need to override the clone () method of the Object class and call the clone () method inside the method that holds the object; note the clone () method of the following code
Public class Husband implements Cloneable {private int id; private Wife wife; public Wife getWife () {return wife;} public void setWife (Wife wife) {this.wife = wife;} public int getId () {return id;} public void setId (int id) {this.id = id } public Husband (int id) {this.id = id;} @ Override public int hashCode () {/ / myeclipse automatically generated final int prime = 31; int result = 1; result = prime * result + id; return result;} @ Override protected Object clone () throws CloneNotSupportedException {Husband husband = (Husband) super.clone () Husband.wife = (Wife) husband.getWife () .clone (); return husband;} @ Override public boolean equals (Object obj) {/ / myeclipse automatically generated if (this = = obj) return true; if (obj = = null) return false; if (getClass ()! = obj.getClass ()) return false Husband other = (Husband) obj; if (id! = other.id) return false; return true;} / * * @ param args * @ throws CloneNotSupportedException * / public static void main (String [] args) throws CloneNotSupportedException {Wife wife = new Wife (1, "jin"); Husband husband = new Husband (1) Husband husband2 = null; husband.setWife (wife); husband2 = (Husband) husband.clone (); System.out.println ("husband class same=" + (husband.getClass () = = husband2.getClass (); / / true System.out.println ("husband object same=" + (husband==husband2)); / / false System.out.println ("husband object equals=" + (husband.equals (husband) / / true System.out.println ("wife class same=" + (husband.getWife (). GetClass () = = husband2.getWife (). GetClass ()); / / true System.out.println ("wife object same=" + (husband.getWife () = = husband2.getWife (); / / false System.out.println ("wife object equals=" + (husband.getWife (). Equals (husband.getWife (); / / true}}
However, there are some shortcomings: if there are N object properties in the Husband, you suddenly change the structure of the class, and you have to modify the clone () method again.
Solution: you can use Serializable to use deserialization to call the readObject () method of the java.io.ObjectInputStream object.
This is the end of the content of "what is the use of clone () and Cloneable interfaces in Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.