0

I'm making a program that constructs a set that takes in a variety of objects. However, when I try to clone the set I'm getting CloneNotSupportedException, despite declaring CloneNotSupportedException and implementing the Cloneable interface.

Here's the code,

import java.util.ArrayList;

public class NewSet implements Cloneable {

private ArrayList<Object> objects;

     public NewSet() {
          this.objects=new ArrayList<Object>();
     }

     public void add(Object b) {
          if(this.contains(b)) { 
               return;
          }
          else {
               objects.add(b);
          }
     }

      public boolean contains(Object h) { 
          for(int x=0; x<this.size(); x++) {
               if(this.get(x)==h) {
                    return true;
               }

          }
          return false;
     }
      public Object get(int i) {
          return objects.get(i);
     }  

      public int size() {
          return objects.size(); 
     }

 public Object clone() throws CloneNotSupportedException {
          NewSet copy= (NewSet) super.clone();
          return copy;
     }

 public static void main(String[] args) {
   NewSet mb= new NewSet();
          mb.add("b");
          mb.add("c");
          mb.add("d");
          Object mc=mb.clone();
}
}

Any help would be appreciated.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Dio
  • 1
  • 3

2 Answers2

3

You're not getting a CloneNotSupportedException. You're getting an error from the compiler, taht says that since the clone method throws CloneNotSupportedException, you need to either catch the exception, or declare it in the throws clause, like any other checked exception:

unreported exception java.lang.CloneNotSupportedException; must be caught or declared to be thrown

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

You're getting that error because clone() can delegate a CloneNotSupportedException to the caller, but you're handling possible exception there. To do so surround the Object mc=mb.clone(); line in the main method with a try/catch block:

public static void main(String[] args) {
    NewSet mb = new NewSet();
    mb.add("b");
    mb.add("c");
    mb.add("d");
    Object mc = null;
    try {
        mc = mb.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
}

Now the main method handles a possible CloneNotSupportedException exception for the method call mb.clone().

Another way to handle that Exception in the main method could be to add throws to the method:

public static void main(String[] args) throws CloneNotSupportedException {
    NewSet mb = new NewSet();
    mb.add("b");
    mb.add("c");
    mb.add("d");
    Object mc = mb.clone();
}
Tom
  • 16,842
  • 17
  • 45
  • 54