2014-12-13 51 views
0

我目前正在使用HashMaps替換ArrayLists中的項目,並且遇到問題。在我的代碼的這一部分中,我從我的書課堂創建了一個新的「書」,並且在「獲得書」部分中是我遇到問題的地方。我正在試圖檢查(現在的)HashMap書籍,看看getId()方法中的書籍ID是否與書籍對象的bookID匹配。我應該如何去使用Book對象迭代我的HashMap?用HashMap替換ArrayLists

這是我的HashMap:HashMap<String, String> books = new HashMap<String, String>();

 if (users.containsValue(new User(userID, null, 0)) 
       && books.containsValue(new Book(bookID, null))) { 
      // get the real user and book 
      Book b = null; 
      User u = null; 

     // get book 
      for (Book book : books) { 
       if (book.getId().equalsIgnoreCase(bookID)) { 
        b = book; 
        break; 
       } 
      } 
+2

你打算在HashMap中放什麼?關鍵是什麼?價值是什麼? – Eran 2014-12-13 12:14:18

+0

你確定你在這裏正確地代表你的書'HashMap'嗎?書籍「HashMap」中包含哪些信息? 'books'似乎不是'HashMap'的好名字,'Map'對象應該用於*關係*,用於合成的類。 – 2014-12-13 12:34:40

+0

你的意圖不明確。如果你能更好地解釋可能是我們可以提供幫助。在你的代碼中,'books'是一個帶有String鍵的hashMap,你正在嘗試匹配字符串鍵和一個永遠不會是真的Object。 – Dileep 2014-12-13 12:44:58

回答

0

只有字符串在你的HashMap中。 沒有書。

由於HashMap中沒有書籍,您將永遠無法從中獲取Book對象。

如果你想找出書String對象,一個HashMap工作對象,但你必須將它設置了這種方式:

HashMap<String, Book> books = new HashMap<String, Book>(); 

這裏有一個如何HashMap的可搭配使用全工作示例預訂對象:

import java.util.HashMap; 

public class Book 
{ 
    private String title; 
    private int pages; 

    public Book(String title, int pages) 
    { 
     this.title = title; 
     this.pages = pages; 
    } 

    public String toString() 
    { 
     return title + ", " + pages + "p."; 
    } 

    public static void main(String[] args) 
    { 
     //creating some Book objects 
     Book theGreatBook = new Book("The great Book of awesomeness", 219); 
     Book klingonDictionary = new Book("Klingon - English, English - Klingon", 12); 

     //the Map: 
     HashMap<String, Book> library = new HashMap<String, Book>(); 

     //add the books to the library: 
     library.put("ISBN 1", theGreatBook); 
     library.put("ISBN 2", klingonDictionary); 

     //retrieve a book by its ID: 
     System.out.println(library.get("ISBN 2")); 
    } 
} 

爲什麼使用字符串來識別對象? 字符串不是唯一的,所以如果兩本書有相同的ID,就會遇到問題。 我會將對象的ID作爲數據字段添加到對象本身。 將一個ID與一個HashMap中的對象關聯起作用,但非常失敗。 沒有地圖,關聯就消失了。 它也容易出錯,因爲編譯器無法緩存字符串中的拼寫錯誤。 也許你在運行時遇到NullPointerException。

特別是因爲你的用戶類也有這樣的「ID」,我想知道你是否把這個添加到每個類中,並且想說實際上沒有必要這樣做(除非你有其他原因)。 要標識一個對象,只需使用該對象的引用即可。 如果您在引用對象的其中一個變量名中有拼寫錯誤,編譯器將能夠告訴您這樣做。

0

你可能需要這樣的東西。我使用的是名字而不是ID,但我希望你能得到漂移...

// setting up the test 
HashMap<String, String> borrowers = new HashMap<String, String>(); 
borrowers.put("Lord of the Rings", "owlstead"); 
borrowers.put("The Hobbit", "sven"); 
borrowers.put("Vacuum Flowers", "owlstead"); 

// find out what I borrowed from the library 

String userID = "owlstead"; 
List<String> booksBorrowed = new ArrayList<>(); 
// iterating through the books may not be very efficient! 
for (String bookName : borrowers.keySet()) { 
    if (borrowers.get(bookName).equals(userID)) { 
     booksBorrowed.add(bookName); 
    } 
} 

// print instead of a return statement 
System.out.println(booksBorrowed);