Equals method on list of lists

java arraylist equals

519 просмотра

1 ответ

83 Репутация автора

Let this be a definition of a matrix:

private List<<List<Object>> lines;

public boolean equals(Object o){
      if(this==o)
         return true;
      if((o==null) || (this.getClass()!=o.getClass()))
         return false;
      Matrix m = (Matrix) o;
      return ????;
}

how can I compare all those lines and columns.

Can I just use

return this.lines.equals(o.getLines());

??

Thanks

Автор: Richard Источник Размещён: 18.07.2016 06:10

Ответы (1)


2 плюса

3847 Репутация автора

More or less, though that exact code doesn't quite work.

From the List.equals javadoc:

Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).)

You can indeed use this method to determine equality, but you need to cast o first. This is a safe cast because you already checked the class (though you might consider using instanceof Matrix instead).

return this.lines.equals(((Matrix)o).getLines());
Автор: Zircon Размещён: 18.07.2016 06:15
Вопросы из категории :
32x32