java clone()方法

Python013

java clone()方法,第1张

虽然clone是Object就有的方法,但是想用必须实现Cloneable接口,String没有实现这个接口

所以这么提示,The method clone() from the type Object is not visible

从Object继承过来的clone方法不可见

从楼主对回答的追问上发现,楼主的连JAVA基本的语法都很差啊。=号是赋值运算符,不是比较。

double[] vectorValue

vectorValue = vectorValue.clone()

这个段代码执行肯定报错了。但他还的意思还是很明确的。

首先:double[] vectorValue  这个是定义了一个double类型的数组变量vectorValue。

其次:vectorValue = vectorValue.clone() //这个是将vectorValue 克隆一份,赋值给自己。也就是说vectorValue变量指向了新的一块内存区域。

举个例子可能更能说明问题。

public class TestMain implements Cloneable {

private int i 

public TestMain(int i){

this.i = i 

}

@Override

protected Object clone() {

// TODO Auto-generated method stub

return new TestMain(this.getI()+1)

}

public int getI() {

return i

}

/**

 * @param args

 */

public static void main(String[] args) {

// TODO Auto-generated method stub

TestMain tm1 = new TestMain(1)

TestMain tm2  = tm1

tm1 = (TestMain)tm1.clone()

System.out.println(tm1.getI()) //tm1指向的是通过clone()方法创建的新的对象的地址,i的值已经是2了。

System.out.println(tm2.getI()) //tm2指向的还是tm1创建时的地址,i的值为1

}

}

1、Cloneable接口只是个标记接口,里面没有任何实现方法,不实现Cloneable接口也可以使用Object的clone方法

2、任何类都是Object的子类,在子类里当然可以直接调用clone方法,比如super.clone()

3、注意clone方法用native修饰,表明该方法有方法体只是调用的jre外部方法,一般是用C语言实现,其作用是通过jvm和操作系统底层交互

4、参照3