0

我定义了一个 Map ,并存放在里面的对象,我想修改里面的键,值怎么修改?代码如下:

package maptest;

/**
 * test Map
 * 
 * @author admin
 *@version 2012.8.29
 */

public class TestA {

private String name;
private String password;
private String idnum;

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

public String getName() {
    return name;
}

// password

public void setPassword(String password) {
    this.password = password;
}

public String getPassword() {
    return password;
}

// idnum

public void setIdnum(String idnum) {
    this.idnum = idnum;
}

public String getIdnum() {
    return idnum;
}

}

===========================================================

    package maptest;

import java.util.HashMap;
import java.util.Map;

/**
 * Test Map
 * 
 * @author admin
 *@version 2012.8.29
 */

public class TestB {

Map<Object, Object> map = new HashMap<Object, Object>();// map.

public void show() {
    TestA tes = new TestA();
    tes.setName("a");// name
    tes.setPassword("a123");// password
    tes.setIdnum("01");// idnum

    map.put(tes, tes);// add map.

    TestA tes1 = new TestA();

    tes1.setName("b");// name
    tes1.setPassword("a1234");// password
    tes1.setIdnum("02");// idnum

    /*
     * Assuming in accordance setIdnum ("02"), how to delete the name and
     * password of it belongs to?
     */

    map.put(tes1, tes1);// add map.

    TestA tes2 = new TestA();

    tes2.setName("c");// name
    tes2.setPassword("a12345");// password
    tes2.setIdnum("03");

    /*
     * Assuming in accordance setIdnum ("03") to find the name and password,
     * and then modify one of the password, concrete should be how to
     * achieve?
     */

    map.put(tes2, tes2);// add map.
}

public void showmap() {// show map
    for (Object c : map.keySet()) {
        System.out.println("Name>>>:" + ((TestA) map.get(c)).getName());
        System.out.println("Password>>>:"
                + ((TestA) map.get(c)).getPassword());
        System.out.println("Idnum>>>:" + ((TestA) map.get(c)).getIdnum());
        System.out.println("---------------------");
    }
    System.out.println("end.");
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    TestB te = new TestB();
    te.show();
    te.showmap();
}

}

==========================================

List and Set 删除和修改以及 Map?

4

2 回答 2

0

你可以利用

map.keySet().remove(obj);
于 2012-08-29T05:43:56.873 回答
0

java.util.Map.put(K k, V v)实际上做了两件事。

1)如果在地图中找不到密钥,它会添加一个条目

2) 如果它为提到的键找到一个条目,它会修改一个条目的值。

当我们调用时会发生移除java.util.Map.remove(K k)。它删除包含键值对的条目。

于 2012-08-29T05:40:43.410 回答