2014-12-13 39 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);