Map map = new HashMap();
Dog dog = new Dog("Big Dog");map.put(dog.getName(), dog);当用户修改 dog.setName("BigBig Dog");我希望 map key 同时也更改..怎样可以实现?
Dog dog = new Dog("Big Dog");map.put(dog.getName(), dog);当用户修改 dog.setName("BigBig Dog");我希望 map key 同时也更改..怎样可以实现?
如何改..有这个api 吗?
dog.setName("BigBig Dog");
map.put(dog.getName(), dog);
所以我用了 hashMap, 问题就是当书名, 改了hashMap key, 没有一同修改.
若然delete 该书再输入一个新的, 其它参照这个数据就失效。之前用vector….若然要找某本书, 就需要历遍整个vector才找到 请问我应该用哪种集合??
增加一个静态方法以获得这个 Map,同时在 setName 方法中进行处理。import java.util.HashMap;
import java.util.Map;public class Test2 {
public static void main(String[] args) {
Map<String, Dog> map = Dog.getMapInstance();
Dog a = new Dog("Big Dog", 2, "dog1_address");
Dog b = new Dog("Little Dog", 2, "dog2_address");
Dog c = new Dog("BigBig Dog", 2, "dog3_address");
for(Map.Entry<String, Dog> entry : map.entrySet()) {
System.out.println(entry.getKey() + " --> " + entry.getValue().getAddress());
}
System.out.println();
c.setName("BigBigBig Dog");
for(Map.Entry<String, Dog> entry : map.entrySet()) {
System.out.println(entry.getKey() + " --> " + entry.getValue().getAddress());
}
}
}class Dog {
private static Map<String, Dog> map = new HashMap<String, Dog>();
private String name = null;
private int age = 0;
private String address = null;
public Dog(){
}
public Dog(String name, int age, String address) {
setName(name);
setAge(age);
setAddress(address);
}
public static Map<String, Dog> getMapInstance() {
return map;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
// 设置名字时若已有重复的,则不能重设名字
if(map.containsKey(name) && map.get(name) != this) {
throw new IllegalArgumentException(name + " has existed!");
}
Dog tmp = null;
if(this.name == null) {
// 如果是新 Dog,就直接添加
tmp = this;
} else {
// 如果是老 Dog 改名字,则重置
tmp = map.remove(this.name);
}
this.name = name;
map.put(this.name, tmp);
}
}