2013-08-06 102 views
2

我有HashMap与ArrayList作为键和值作为整数,我如何从特定的键获得值。如何实现具有数组列表作为键的映射

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] 

在我的程序中有几次在不同的地方我需要为特定的键找到一个特定的值。我不想使用循环evry时间来获得价值。 我该怎么做?

+12

这是一个坏主意。使用集合作为键很少是一个好主意 –

+0

这将是非常困难的。 – tbodt

+0

看你如何使用它,你真的可能想要为'Brand','Launch','Model'和'ProducerPrice'单独创建类。 – bas

回答

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; 
    } 
} 

然后利用命题一个HashMap对象

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 
} 
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 

同样,这很可能是一个坏主意。直到你修改添加后列表本身

propositionMap.get(arrayListN) 

0

你可以得到价值通常的方式。