Provide Best Programming Tutorials

The Cloneable Interface

Often, it is desirable to create a copy of an object. To do this, you need to use the clone method and understand the Cloneable interface.

An interface contains constants and abstract methods, but the Cloneable interface is a special case. The Cloneable interface in the java.lang package is defined as follows:

package java.lang;
public interface Cloneable {
}

This interface is empty. An interface with an empty body is referred to as a marker interface . A marker interface is used to denote that a class possesses certain desirable properties. A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using the clone() method defined in the Object class.

Many classes in the Java library (e.g., Date , Calendar and ArrayList ) implement Cloneable . Thus, the instances of these classes can be cloned. For example, the following code:

1 Calendar calendar = new GregorianCalendar(2013, 2, 1);
2 Calendar calendar1 = calendar;
3 Calendar calendar2 = (Calendar)calendar.clone();
4 System.out.println("calendar == calendar1 is " +
5 (calendar == calendar1));
6 System.out.println("calendar == calendar2 is " +
7 (calendar == calendar2));
8 System.out.println("calendar.equals(calendar2) is " +
9 calendar.equals(calendar2));

displays

calendar == calendar1 is true
calendar == calendar2 is false
calendar.equals(calendar2) is true

In the preceding code, line 2 copies the reference of calendar to calendar1 , so calendar and calendar1 point to the same Calendar object. Line 3 creates a new object that is the clone of calendar and assigns the new object’s reference to calendar2 . calendar2 and calendar are different objects with the same contents.

The following code:

ArrayList<Double> list1 = new ArrayList<>();
list1.add(1.5);
list1.add(2.5);
list1.add(3.5);
ArrayList<Double> list2 = (ArrayList<Double>)list1.clone();
ArrayList<Double> list3 = list1;
list2.add(4.5);
list3.remove(1.5);
System.out.println("list1 is " + list1);
System.out.println("list2 is " + list2);
System.out.println("list3 is " + list3);

displays

list1 is [2.5, 3.5]
list2 is [1.5, 2.5, 3.5, 4.5]
list3 is [2.5, 3.5]

 

 

Leave a Reply

Close Menu