天天看點

Cloneable接口使用

一.簡介

Clone方法是可以建立對象的一種方式。使用clone方法複制對象。由于clone方法将最終将調用JVM中的原生方法完成複制也就是調用底層的c++代碼,是以一般使用clone方法複制對象要比建立一個對象然後逐一進行元素複制效率要高。

二.舉例使用

Java Bean

public class Student implements Cloneable {

    private String name;
    private String sex;
    private String age;

    public Student(){

    }

    public Student(String name,String sex,String age){
        this.name=name;
        this.sex=sex;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public Object clone() {
        Student student=null;
        try {
            student= (Student) super.clone();
            student.name=this.name;
            student.sex=this.sex;
            student.age=this.age;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return student;
    }

    public String toString(){
        return "姓名:"+name+"  性别:"+sex+"  年齡:"+age;
    }
}
           

代碼調用

private void CloneableMethod(){
   Student student=new Student();
   student.setAge("28");
   student.setName("張三");
   student.setSex("男");

   Student clonestudent=null;
   clonestudent= (Student) student.clone();
   String result1="原有對象\n姓名:"+student.getName()+"\n性别:"+student.getSex()+"\n年齡:"+student.getAge(); 
   Log.d("TAG","result1----:"+result1); 
   Log.d("TAG","------------------------------------------------------------------------------");
   String result2="克隆對象\n姓名:"+clonestudent.getName()+"\n性别:"+clonestudent.getSex()+"\n年齡:"+clonestudent.getAge(); 
   Log.d("TAG","result2----:"+result2);
}
           

結果

result1----:原有對象
姓名:張三
性别:男
年齡:28
------------------------------------------------------------------------------
result2----:克隆對象
姓名:張三
性别:男
年齡:28