2016-12-15 59 views
0

將多個對象作爲密鑰存儲在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 

請建議我在哪裏錯把多個對象作爲重點,

+1

您的地圖的關鍵是字符串,所以你只能把字符串作爲鍵。 – Eran

+0

你已經指定你的地圖鍵是一個字符串,而不是'Allien'或'Predator'。你是如何期望這項工作的?也許你想要'Map >'? –

+0

謝謝,它是我身邊的一個愚蠢的錯誤。 – Kaustav

回答

0

使用一個對象作爲HashMap中的關鍵字地圖聲明,重點對象必須重寫的hashCode等於方法。

請參見下面的樣品,它給輸出「這是人100」:

public class HashMapSample { 
    public static void main(String[] args) { 
     Map<Person, String> map = new HashMap<Person, String>(); 
     map.put(new Person(100, "name 100"), "this is person 100"); 
     map.put(new Person(200, "name 200"), "this is person 200"); 

     Person key = new Person(100, "new name 100"); 
     if (map.containsKey(key)) { 
      System.out.println(map.get(key)); 
     } else { 
      System.out.println("NOT FOUND"); 
     } 
    } 
} 

class Person { 
    int id; 
    String name; 

    public Person (int id, String name) { 
     this.id = id; 
     this.name = name; 
    } 

    @Override 
    public int hashCode() { 
     return id; 
    } 
    @Override 
    public boolean equals(Object obj) { 
     if (obj instanceof Person) { 
      Person person = (Person) obj; 
      return person.id == this.id; 
     } 
     return false; 
    } 

    public int getId() { 
     return id; 
    } 
    public void setId(int id) { 
     this.id = id; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
} 
1

您已指定您的地圖密鑰字符串,但需要的對象。您需要更改像下面

Map<Object, ArrayList<String>> productsMap = new HashMap<>();