0

I have an array list of book objects where one of the class fields is title. I want to search through the array for a book with a specific title value.

public void getBook(String bookTitle) throws SQLException {

    ArrayList<Book> books = getAllBooks();

    for (int i = 0; i < books.size(); i++) {
        Book b = books.get(i);
        if (b.getTitle() == bookTitle) {
            System.out.println(b.getTitle());
        } 

    }

} 

As far as I can tell the code above should search through the array list for book objects and compare their title field with the string passed into the function. If the strings match then the book title will be printed to console. However nothing happens. Help :(

Jeremy
  • 22,188
  • 4
  • 68
  • 81
  • 1
    You are comparing the reference of book title in your code which obviously is going to be different. So if you really want to compare the content of strings then try this `b.getTitle().equals(bookTitle)` – BeginnersSake Mar 08 '17 at 17:25
  • you probably also want to break out of the loop once found. – MeBigFatGuy Mar 08 '17 at 17:38
  • Thanks that was the problem. – Daniel Eden Mar 08 '17 at 17:45
  • Of course it is a duplicate. I had no idea what the problem was so had no way to know to look for "how to compare string values" as I didn't know that was my problem. This is just like when I was in primary school and the teacher had a go at me for now being able to find the correct spelling of "which" in the dictionary because I was spelling it "witch" and had no idea there was a "h" in it. If I get banned form stack overflow for that that is beyond moronic. – Daniel Eden Mar 08 '17 at 17:48
  • I'm only using a small database so there is no real need to break out of the for loop but it would be useful to know for future use? – Daniel Eden Mar 08 '17 at 17:51

1 Answers1

2

It looks like you need to use the 'equals' method for string comparison:

b.getTitle.equals(bookTitle)

There is an answer here that describes why:

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Community
  • 1
  • 1
superPants
  • 21
  • 2