Hayes121 Hayes121 - 1 year ago 133
Java Question

Java looping through Object list and attributes

I am trying to implement a function that will loop through a list of objects and then with an inner loop compare one of the objects attributes with a string, if the string is a match return true and if not false.

I am having some trouble with the inner loop of looping through the attributes.

Below is the class that I am using, I am adding the new books to the store list and then trying to loop through the list in the findBookBName function.


public class Book {

private String title;
private String author;
private String published;

public Book(String title2, String author2, String published2) {
this.title = title2;
this.author = author2;
this.published = published2;

public class Library {
private List<Book> store = new ArrayList<>();

public void addBook(final Book book) {

public void findBookByName(String bookSearch) {
for(int i = 0; i < store.size(); i ++) {
String title = book[i].name; //trying to look at name attribute of the first book object(book1) - this is incorrect
if(title == bookSearch) {
return true;
} else {
return false;

Answer Source



Strings should not be compared with ==.

For the attribute's retrieval part, it should be

 String title = store.get(i).name;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download