1

I need to make a copy of the following object and compare it to the original but I have no idea where to begin.

Administrator admin = new Administrator(first, last, 
     new Date(month,day,year), salary, title, department, supervisor);

I have tried researching copy and clone methods but I can not seem to grasp it.

Vasu
  • 21,832
  • 11
  • 51
  • 67
RalphOrDie
  • 15
  • 3

1 Answers1

0

In order to use the clone method, your classes must implement the Cloneable interface.

Check the sample code below.

public class MyClass implements Cloneable {
   private String text;
   private int size;

   public String getText() {
      return text;
   }
   public void setText(String text) {
      this.text = text;
   }
   public int getSize() {
      return size;
   }
   public void setSize(int size) {
      this.size = size;
   }

   public MyClass clone() throws CloneNotSupportedException{
      return (MyClass)super.clone();
   }
}

Cloning...

try{
   MyClass myClass = new MyClass();
   myClass.setSize(6);
   myClass.setText("sample");

   MyClass myClass2 = myClass.clone();
} catch(Exception e){
   e.printStackTrace();
}

Make sure that you override the equals method properly for object comparison.

Noel
  • 91
  • 3
  • Don't swallow exceptions. Fix the warnings in your code. What if the object contains other mutable objects; do you need a shallow or a deep clone? – Robert Dec 07 '16 at 03:41
  • It is just a sample. It is true that exception may occur especially when there are objects that are not cloneable. – Noel Dec 07 '16 at 04:57