0

If there is an ArrayList for moviesAvailable and the list takes title, year, genre, price. How can I get a list of movies using an ArrayList of genres?

There is a toString method in the Movie class that prints out the movies. When I run the code everything past the if statement doesn't run because the condition is returned as false.

1
  • 2
    You can clearly see that you are calling the "equals" method of Genre, but you didn't override it, so you are using the default one, which is wrong. Commented May 10, 2019 at 14:19

2 Answers 2

1

You need to override equals() in your Genre class, so that you can compare instances of that class to each other.

Here's a quick implementation, which can easily be extended for additional functionality:

@Override
public boolean equals(Object o) {
    if (!(o instanceof Genre)) {
        return false;
    }
    return ((Genre) o).name.equals(this.name);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Your method also is not null save. new Genre(null).equals(new Genre(null)) throws a NullPointerException.
@SamuelPhilipp "Here's a quick implementation, which can easily be extended for additional functionality"
This method works, is this the only way to solve the problem or there there anything I can change in the code to make it work?
@TDizzle Overriding the equals() method is exactly what your code needed.
0

You need to override equals method in Genre class to make if condition working, see below code

private String name;

Genre(String name){
    this.name = name;
}
public boolean hasType(String genre) {

    return genre.equals(this.name);
}

public boolean equals(Object o) {
   if (!(o instanceof Genre)) {
      return false;
   }
   return this.name.equals(((Genre)o).name);
}

1 Comment

a better implementation would be: return (o instanceof Genre) ? ((Genre) o).name.equals(this.name) : false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.