即使我使用泛型,也会在Map中将多个对象存储为键。
ArrayList<String> fruitlist = new ArrayList<>();
fruitlist.addAll(Arrays.asList("Apple", "Banana", "Grapes"));
ArrayList<String> vegglist = new ArrayList<>();
vegglist.addAll(Arrays.asList("Potato", "Squash", "Beans"));
Map<String, ArrayList<String>> productsMap = new HashMap<>();
Allien a = new Allien(101, "John"); //creted sperated Allien class and constructor
Predator p = new Predator(102, "Lisa"); // creted sperated Predator class and constructor
productsMap.put(a, fruitlist); //compile time error change type a as String
productsMap.put(p, vegglist); // same error
请建议将多个对象作为键放在哪里我错了,
答案 0 :(得分:1)
您已将Map键指定为字符串,但需要一个对象。你需要改变你的地图声明,如下所示
Map<Object, ArrayList<String>> productsMap = new HashMap<>();
答案 1 :(得分:0)
要将对象用作HashMap中的键,关键对象必须覆盖 hashCode 和等于方法。
见下面的示例,它给出输出“这是人100”:
Hotel Market Desc Date Values
ABC France SUP HB Jan16 158
ABC France SUP HB Feb16 33
ABC France SUP AI Jan16 35
ABC France SUP AI Feb16 6
ABC France DLX HB Jan16 27
ABC France DLX HB Feb16 10