Spaces:
Running
Running
| Class 'Movie' is defined in the following program. | |
| Write the 'equals' method to the class using the examples in this page. | |
| 2 movies are equal, if ALL ATTRIBUTES have 'equal values'; | |
| hence, the name, director and length should be equal. | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.Collections; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| Movie m = new Movie("Java and Me", "James Javason", 93); | |
| System.out.println("Movie: " + m); | |
| Movie m2 = new Movie("Java and Me", "Jane Javander", 93); | |
| Movie m3 = new Movie("Java and Me", "James Javason", 94); | |
| Movie m4 = new Movie("Python and me", "James Javason", 93); | |
| Movie m5 = new Movie("Java and Me", "James Javason", 93); | |
| ArrayList<Movie> movies = new ArrayList<>(Arrays.asList(new Movie[] {m2,m3,m4,m5,m,null})); | |
| Collections.shuffle(movies, r); | |
| movies.stream().forEach(mo -> compare(m, mo)); | |
| System.out.println("Comparing to String \"Java and Me\""); | |
| System.out.println("equals: " + (m.equals("Java and Me"))); | |
| } | |
| public static void compare(Movie m, Movie m2) { | |
| System.out.println("Comparing to movie " + m2); | |
| System.out.println("equals: " + (m.equals(m2))); | |
| } | |
| } | |
| class Movie { | |
| private String director; | |
| private String name; | |
| int length; | |
| public Movie(String director, String name, int length) { | |
| this.director = director; | |
| this.name = name; | |
| this.length = length; | |
| } | |
| public String toString() { | |
| return name + " (" + director + "), " + length + " min."; | |
| } | |
| public boolean equals(Object m2) { | |
| // same object | |
| if (this == m2) { | |
| return true; | |
| } | |
| // not null | |
| if (m2 == null) { | |
| return false; | |
| } | |
| // not 'Movie' class | |
| if (m2.getClass() != Movie.class) { | |
| return false; | |
| } | |
| // convert into an object | |
| Movie other = (Movie) m2; | |
| // same values | |
| if (this.director.equals(other.director) && this.name.equals(other.name) && this.length == other.length) { | |
| return true; | |
| } | |
| else { | |
| return false; | |
| } | |
| } | |
| } | |
| Movie: James Javason (Java and Me), 93 min. | |
| Comparing to movie James Javason (Python and me), 93 min. | |
| equals: false | |
| Comparing to movie James Javason (Java and Me), 93 min. | |
| equals: true | |
| Comparing to movie Jane Javander (Java and Me), 93 min. | |
| equals: false | |
| Comparing to movie James Javason (Java and Me), 94 min. | |
| equals: false | |
| Comparing to movie null | |
| equals: false | |
| Comparing to movie James Javason (Java and Me), 93 min. | |
| equals: true | |
| Comparing to String "Java and Me" | |
| equals: false | |