Arraylist Java绑定错误

时间:2013-03-22 08:15:03

标签: java arraylist

我需要为学校项目创建自己的注册表。

我想

1
room, room
2
room, room
hall, hall
3
room, room
hall, hall
dorm, dorm

但我得到的只是

1
room,room
2
room,hall
hall,hall
3
room,dorm
hall,dorm
dorm,dorm

所以不知怎的,设施参考在某处改变了,但我不知道如何解决这个问题。有人可以帮忙吗?

这些是我的代码。

public class registry {
static List<registryRecord> register = new ArrayList<registryRecord>();
public static boolean bind(String name, facility ref){
    for(registryRecord r:register){
        if(r.name.equals(name)) //check if the name is already binded
            return false;
    }
    registryRecord newRecord = new registryRecord(name, ref);
    register.add(newRecord);
    for (registryRecord r:register){
        System.out.println(r.name +","+ r.ref.name);
    }
    return true;
}

public class registryRecord {
String name;
facility ref;
public registryRecord(String name, facility ref){
    this.name = name;
    this.ref = ref;
}

public class server {
public static void main(String args[]) throws Exception{  
    facility room = new facility("room");
    System.out.println(1);
    boolean test = registry.bind("room", room);
    facility hall = new facility("hall");
    System.out.println(2);
    boolean test2 = registry.bind("hall", hall);
    facility dorm = new facility("dorm");
    System.out.println(3);
    registry.bind("dorm", dorm);
}
public class facility {
    public static String name;
    static List<booking> bookings;

    public facility(String name){
        this.name=name;
        this.bookings = new ArrayList<booking>();
    }
}

1 个答案:

答案 0 :(得分:1)

正如我所怀疑的那样,name staticfacilitystatic,所有实例之间共享。这意味着每次创建新实例时都会被覆盖。

只需从您的两个字段中删除{{1}},您的程序就可以正常运行。

相关问题