这个Java HashMap声明有什么问题?简单点

时间:2010-12-18 01:12:17

标签: java hashmap declaration

private HashMap<String, IMapper> mapper = new HashMap<String, IMapper>();

看起来如此无辜,但Eclipse正在抱怨所有事情的分号。

Eclipse错误:令牌“;”上的语法错误,AssignmentOperator

无效

由于

全班:

package persistence;

import java.util.UUID;
import java.util.HashMap;

import domain.Task;

public class PersistanceFacade {

    private static PersistanceFacade uniqueInstance = null;
    private HashMap<String, IMapper> mapper = new HashMap<String, IMapper>();


    (SingleTaskRDBMapper) mapper.put("SingleTask", new SingleTaskRDBMapper());

    public PersistanceFacade() {};

    public static synchronized PersistanceFacade getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new PersistanceFacade();
            return uniqueInstance;
        }
        else return uniqueInstance;
    }

    @SuppressWarnings("unchecked")
    public Object get(UUID oid, Class type) {
        Object mappers;
        IMapper mapper = ((HashMap<String, IMapper>) mappers).get(type);
    }

}

3 个答案:

答案 0 :(得分:4)

该行

(SingleTaskRDBMapper) mapper.put("SingleTask", new SingleTaskRDBMapper());

不合适。你应该把它放在构造函数中:

public PersistanceFacade() {
  mapper.put("SingleTask", new SingleTaskRDBMapper());
}

另请注意,我在构造函数的右大括号后删除了无关的分号。我也不确定get方法中发生了什么。您声明对象mappers但从不初始化它。这肯定会导致错误。

答案 1 :(得分:1)

不确定IMapper是什么,我假设某个界面,但我把它放到Eclipse中并且它没有给我任何错误:

private interface IMapper {}
private HashMap<String, IMapper> mapper = new HashMap<String, IMapper>();

也许您可以发布更多代码?

答案 2 :(得分:1)

此代码完美运行:),灵感来自laz的帮助

package persistence;

import java.util.UUID;
import java.util.HashMap;

public class PersistanceFacade {

    private static PersistanceFacade uniqueInstance = null;
    private HashMap<String, IMapper> mappers = new HashMap<String, IMapper>();

    public PersistanceFacade() {
        mappers.put("SingleTask", new SingleTaskRDBMapper());

    }

    public static synchronized PersistanceFacade getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new PersistanceFacade();
            return uniqueInstance;
        }
        else return uniqueInstance;
    }

    @SuppressWarnings("unchecked")
    public Object get(UUID oid, Class type) {
        IMapper mapper = (IMapper) mappers.get(type);
        return mapper.get(oid);
    }

}