2

我有 HashMap,ArrayList 为键,值为 Integer,如何从特定键中获取值。

Map< List<Object>,Integer> propositionMap=new HashMap<List<Object>,Integer>();  

my key are:[Brand, ID], [Launch, ID], [Model, ID], [Brand, UserModelNoMatch], [ProducerPrice, UserModelMatch], [ProducerPrice, ID]]
my values are:[3, 5, 4, 2, 1, 6]

在我的程序中多次在不同的地方,我需要找到特定键的特定值。我不想每次都使用 for 循环来获得价值。我怎样才能做到这一点?

4

3 回答 3

4

撇开这是一个坏主意(如评论中所述)不谈,您不需要做任何特别的事情:

List<Object> list = new ArrayList<Object>();
// add objects to list

Map<List<Object>,Integer> propositionMap = new HashMap<List<Object>,Integer>();  
propositionMap.put(list, 1);
Integer valueForList = propositionMap.get(list); // returns 1

独立构造列表时可以获得相同的值:

List<Object> list2 = new ArrayList<Object>();
// add the same objects (by equals and by hashcode) to list2 as to list

Integer valueForList = propositionMap.get(list2); // returns 1

但需要注意的是,在将列表用作地图中的键后不要更改列表!

list.add(new Object());
Integer valueForList = propositionMap.get(list); // likely returns null

同样,这很可能是个坏主意。

于 2013-08-06T10:56:45.630 回答
0

鉴于您想要相同的行为,我强烈建议您使用带类的接口。

public interface Proposition
{
    public int getID();
}

public class Brand implements Proposition
{
    private int id;

    public Brand(int _id_)
    {
        this.id = _id_;
    }

    public int getID()
    {
        return this.id;
    }
}

public class Launch implements Proposition
{
    private int id;

    public Launch(int _id_)
    {
        this.id = _id_;
    }

    public int getID()
    {
        return this.id;
    }
}

public class ProducerPrice implements Proposition
{
    private int id;
    private int UserModelMatch;

    public ProducerPrice(int _id_, int _UserModelMatch_)
    {
        this.id = _id_;
        this.UserModelMatch = _UserModelMatch_;
    }

    public int getID()
    {
        return this.id;
    }

    public int getUserModelMatch()
    {
        return this.UserModelMatch;
    }
}

然后对命题对象使用哈希图

Map<Integer, Proposition> propositionMap = new HashMap<Integer, Proposition>();

Proposition newprop = new ProducerPrice(6, 1);
propositionMap.put(newprop.getID(), newprop);

Proposition someprop = propositionMap.get(6);

if (someprop instanceof ProducerPrice)
{
    ProducerPrice myprodprice = (ProducerPrice)someprop;
    // rest of logic here
}
于 2013-08-06T10:49:58.013 回答
0

您可以像往常一样获取值:

propositionMap.get(arrayListN)

直到您在添加后修改列表本身

于 2013-08-06T11:03:45.900 回答