Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone() in java

Tags:

java

clone

import java.util.*;
import java.lang.*;

public class Test{
    public static void main(String[] argv){
        String s1="abc";
        String s2=(String) s1.clone();
    }    
}

Why this simple test program doesn't work?

like image 618
user1192813 Avatar asked Feb 06 '12 17:02

user1192813


People also ask

What is clone () in Java?

Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.

Where is clone () defined Java?

Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class.

Why do we need clone in Java?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed, so we can use object cloning.

What is clone and copy in Java?

The Java Object clone() method creates a shallow copy of the object. Here, the shallow copy means it creates a new object and copies all the fields and methods associated with the object. The syntax of the clone() method is: object.clone()


2 Answers

clone is a method of the Object class. For a class to be "cloneable" it should implement the marker Cloneable interface. String class doesn't implement this interface and doesn't override the clone method hence the error.

I hope the above snippet is for educational purposes because you should never feel a need to call clone on strings in Java given that:

  1. Strings in Java are immutable. Feel free to share them across methods/classes
  2. There already exists a constructor new String(String) which acts like a copy constructor and is pretty much equivalent to your clone() call.
like image 67
Sanjay T. Sharma Avatar answered Sep 30 '22 20:09

Sanjay T. Sharma


Object.clone() is protected. It is a tricky API to use.

Usually one exposes clone() when one extends Object by broadening the method's visibility.

Clone on any string has little meaning, since it is both final and immutable.

There is a reason to copy a string; that can be done with:

String s1 = ...;
String s2 = new String(s1)
like image 41
Dilum Ranatunga Avatar answered Sep 30 '22 20:09

Dilum Ranatunga