是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
当前回答
如果你使用Spring Framework。有:org.springframework.util.MultiValueMap。
创建不可修改的多值映射:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
或者使用org.springframework.util.LinkedMultiValueMap
其他回答
import java.io.*;
import java.util.*;
import com.google.common.collect.*;
class finTech{
public static void main(String args[]){
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("1","11");
multimap.put("1","14");
multimap.put("1","12");
multimap.put("1","13");
multimap.put("11","111");
multimap.put("12","121");
System.out.println(multimap);
System.out.println(multimap.get("11"));
}
}
输出:
{"1"=["11","12","13","14"],"11"=["111"],"12"=["121"]}
["111"]
这是用于实用功能的Google-Guava库。这就是需要的解决方案。
我们可以创建一个类来拥有多个键或值,该类的对象可以用作map中的参数。 你可以参考https://stackoverflow.com/a/44181931/8065321
是也不是。解决方案是为包含与键对应的2(3或更多)值的值构建一个Wrapper类。
如果你使用Spring Framework。有:org.springframework.util.MultiValueMap。
创建不可修改的多值映射:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
或者使用org.springframework.util.LinkedMultiValueMap
我已经习惯了在Objective c中使用数据字典来实现这一目标,而在Java for Android中却很难获得类似的结果。我最终创建了一个自定义类,然后只做了一个自定义类的hashmap。
public class Test1 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addview);
//create the datastring
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));
}
}
//custom class. You could make it public to use on several activities, or just include in the activity if using only here
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;
}
}