John_Java 2012-12-19 13:57
浏览 445
已采纳

IBM中国研发中心面试题,如何用Java写一个程序达到对象深浅克隆的效果?不能用API

IBM中国研发中心面试题,如何用Java写一个程序达到对象深浅克隆的效果?不能用API。来吧,大家发表意见,全分奉上。

  • 写回答

4条回答 默认 最新

  • gxl1989225 2012-12-19 14:57
    关注

    [code="java"]
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    /**

    • 深/浅克隆
    • @author JohnGao
      /
      public class CloneTest
      {
      /
      *

      • 模拟对象深/浅克隆效果
      • @author JohnGao
      • @param T: 目标克隆对象
      • @throws Exception
      • @return T: 克隆对象
        /
        public static T clone(T t) throws Exception
        {
        /
        实例化字节数组节点流 */
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
        byteArrayOutputStream);

        /* 将目标克隆对象转换成数组 */
        objectOutputStream.writeObject(t);

        /* 返回克隆对象 */
        return (T) new ObjectInputStream(new ByteArrayInputStream(
        byteArrayOutputStream.toByteArray())).readObject();
        }
        }
        [/code]

    [code="java"]
    public int age;
    public StringBuffer str = new StringBuffer();

    @Test
    public void test() throws Exception
    {
        MyTest myTest1 = new MyTest();
        MyTest myTest2 = CloneTest.clone(myTest1);
        System.out.println("myTest1.hashcode: " + System.identityHashCode(myTest1));
        System.out.println("myTest2.hashcode: " + System.identityHashCode(myTest2));
        myTest2.age = 15;
        System.out.println("myTest1.age: " + myTest1.age);
        System.out.println("myTest2.age: " + myTest2.age);
        myTest1.str.append("++++");
        myTest2.str.append("----");
        System.out.println("myTest1.str: " + myTest1.str);
        System.out.println("myTest2.str: " + myTest2.str);
    }
    

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?