search

Home  >  Q&A  >  body text

Java:关于Map的引用传递

public class Student {
    private int id;
    private String name;
 
    public Student() {
    }
 
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "[" + id + ", " + name + "]";
    }
}
Student one = new Student(1, "Tim");
Student two = new Student(2, "Jack");
 
Map<Integer, Student> map = new HashMap<Integer, Student>();
map.put(one.getId(), one);
map.put(two.getId(), two);
 
Student tmp = map.get(1);
tmp.setName("New"); // {1=[1, New], 2=[2, Jack]}

可以发现我将Map中的某项取出来并进行了修改,那么Map中的相应项也会被修改,所以说是引用传递的,但是有些情况我就是想把这个东西拿出来用并作些修改,但是Map的数据作为原始值是不想被变更的,这种情况下应该怎么办呢?

高洛峰高洛峰2889 days ago557

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 09:09:29

    Implement the Cloneable interface, override the clone method, clone a new object and make modifications

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:09:29

    Implement clonable interface in java c# implement IClonable interface and implement clone method. Call this clone method to get an object with a different reference than the original object but the same value.

    reply
    0
  • 阿神

    阿神2017-04-18 09:09:29

    Two methods: use tools; rewrite the clone method yourself

    Various tools:

    Spring BeanUtils
    commons-beanutils
    BeanCopier

    Override clone method

    See CloneDemo.java

    Under Student:

    @Override
    public Student clone(){
        Student student = new Student(id, name);
        return student;
    }
    

    Use

    Student one = new Student(1, "Tim");
    Student two = new Student(2, "Jack");
    
    Map<Integer, Student> map = new HashMap<Integer, Student>();
    map.put(one.getId(), one);
    map.put(two.getId(), two);
    
    Student tmp = map.get(1);
    Student student2 = tmp.clone();
    student2.setName("New");

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:09:29

    Method 1, create a new object with only get method. The Student in your question inherits this object and has set method. In this way, the object you put in the Map without set method is of course unmodifiable

    Method 2, troublesome, monitor the set method of Student, if called, immediately throw an exception, how to monitor, this is very easy.

    reply
    0
  • Cancelreply