Suppose I have the following List
to hold a list of fruits.
Example:
def fruits = ["Apple", "Orange", "Grapes"]
def fruitsBowl = ["Apple", "Grapes", "Orange"]
// Will print false
println(fruits.equals(fruitBowl))
Only after I call .sort()
them will both collection be equal.
fruits.sort()
fruitBowl.sort()
// Will print true
println(fruits.equals(fruitBowl))
Suppose if I had a Book
class, obviously a Book
class will have a list
of authors. For this example, the Authors
class has implemented the Comparator
.
class Book {
private String title;
private List<Author> authors;
Book(title, authors){
// code to initialize left out
authors.sort()
}
My main concern is the equals()
method. If two books are compared, even if the book objects are the same, but list of authors is unsorted, it will return false.
If I were to call .sort()
the same way I call sort on fruits
and fruitsBowl
on the collection holding the list of authors in the Book constructor
, is it bad practice?
If it's bad practice, what should I do to ensure that the equals method works?
Update:
As per the comments suppose if I used a Set
, it makes much more sense, because if the books are written by a list of authors, each name will only appear once, so is doing this also considered bad practice?
class Book {
private String title;
private Set authorsSet;
Book(title, authors){
authorsSet = authors.toSet()
}
A Set
is a collection of unique elements and the equality test will work properly, regardless of order.