这可能比较难解释,但我试着说一下:
我想要将三个整数和一个字符串存储到一个HashMap中,以便我可以从Map中检索数据,但事实证明HashMap只允许使用2个泛型参数而不是4个。
例如:HashMap <String> <Integer> <Integer> <Integer>
(我想做的),但是似乎只能使用2个参数:HashMap <String> <Integer>
。
我最好的猜测是我的想法无法实现。如果是这样,请列出处理类似情况的替代方案。
这可能比较难解释,但我试着说一下:
我想要将三个整数和一个字符串存储到一个HashMap中,以便我可以从Map中检索数据,但事实证明HashMap只允许使用2个泛型参数而不是4个。
例如:HashMap <String> <Integer> <Integer> <Integer>
(我想做的),但是似乎只能使用2个参数:HashMap <String> <Integer>
。
我最好的猜测是我的想法无法实现。如果是这样,请列出处理类似情况的替代方案。
创建一个新的类,其中包含3个Integer
或者int
。
class Triple {
Integer i;
Integer j;
Integer k;
Triple(Integer i,Integer j, Integer k) {
this.i = i;
this.j = j;
this.k = k;
}
}
将这个类与字符串一起放入映射中。
HashMap map = new HashMap<String, Triple>();
map.put("keyString", new Triple(new Integer(1),new Integer(2),new Integer(3)));
map.values()
会给你一个Collection<Triple>
。对于每个Triple,你可以直接访问i,j,k
或者提供一个getter方法。如果你想打印这个Triple
,你可以重写public String toString()
方法。 - oliholzpublic class MyClass {
int a,b,c;
String d;
}
HashMap<String, MyObject>
。你可以间接地得到答案,比如将三个整数组合成一个字符字符串。
int val1=1;
int val2=2;
int val3=3;
Map<String,String> test = new HashMap<String,String>();
test.put("key1", val1+"_"+val2+"_"+val3);
when you wan to get the values, int[] rst = test.get("key1).split("_");
然后你就可以访问你的整数值了。
我觉得你正在尝试将两种不同类型的东西作为哈希映射中的值进行存储。这样做没有问题。只需使用默认构造函数创建哈希映射,然后将Object作为值类型即可。所以new HashMap<String, Object>()
你可以使用 HashMap< 你的键类型, 对象 > 来存储任意对象。
我曾经为此问题苦苦挣扎。最终我创建了一个自定义类的哈希表,这完全奏效了,并允许我在我的类中放置任何属性,并以编程方式提取出这些属性。以下是完整示例。
public class Test1 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addview);
//create the data mapping
HashMap<Integer, myClass> hm = new HashMap<Integer, myClass>();
hm.put(1, new myClass("Car", "Small", 3000));
hm.put(2, new myClass("Truck", "Large", 4000));
hm.put(3, new myClass("Motorcycle", "Small", 1000));
//pull the datastring back for a specific item.
//also can edit the data using the set methods. this just shows getting it for display.
myClass test1 = hm.get(1);
String testitem = test1.getItem();
int testprice = test1.getPrice();
Log.i("Class Info Example",testitem+Integer.toString(testprice));
}
}
class myClass{
private String item;
private String type;
private int price;
public myClass(String itm, String ty, int pr){
this.item = itm;
this.price = pr;
this.type = ty;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getType() {
return item;
}
public void setType(String type) {
this.type = type;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}