456.引用

Reference

Description

Implement the class ReferenceManager. Include the following two methods:

  1. copyValue(Node obj). This would just copy the value from parameter obj to the public attribute node. But obj and node are still two difference instances / objects.

  2. copyReference(Node obj). This would copy the reference from obj to node. So that both node and obj are point to the same object.

Example

ReferenceManager ref = ReferenceManager();
Node obj = new Node(0);
ref.copyValue(obj);
ref.node.val; // will be 0
ref.node; // will be different with obj.

Node obj2 = new Node(1);
ref.copyReference(obj2);
ref.node.val; // will be 1
ref.node; // will be the same with obj2
/**
 * Definition of Node:
 * class Node {
 *     public int val;
 *     public Node(int val) {
 *         this.val = val;
 *     }
 * }
 */
public class ReferenceManager {
    public Node node;
    
    public ReferenceManager(){
        node = new Node();
    }
    
    public void copyValue(Node obj) {
        // copy value from obj to node
        node.val = obj.val;
        
    }

    public void copyReference(Node obj) {
        // copy reference from obj to node
        node = obj;
        
    }
}

描述
实现一个类 ReferenceManager 包含如下两种方法

1.copyValue(Node obj) 只拷贝参数obj的权值,obj和node仍然是两个指针

2.copyReference(Node obj) obj和node指向同一个地方

您在真实的面试中是否遇到过这个题?  
样例
ReferenceManager ref = ReferenceManager();
Node obj = new Node(0);
ref.copyValue(obj);
ref.node.val; // will be 0
ref.node; // will be different with obj.

Node obj2 = new Node(1);
ref.copyReference(obj2);
ref.node.val; // will be 1
ref.node; // will be the same with obj2
posted @ 2019-04-02 22:47  故人叹  阅读(233)  评论(0)    收藏  举报