如何创建一个equals方法来比较数组中的两个对象?

时间:2017-11-20 20:14:51

标签: java

如何比较数组中的每个对象以确定它们是否相同; 恩。比较曲棍球运动员和高尔夫球手,输出他们是不一样的, 或者将两个曲棍球运动员相互比较并输出它们是相同的。

我不确定如何实现这一点。

players[0] = new BaseballPlayer(...stuff);
players[1] = new FootBall(...stuff);
players[2] = new HockeyPlayer(...stuff);
players[3] = new Golfer(...stuff);
players[4] = new BaseballPlayer(...stuff);
players[5] = new FootBall(...stuff);
players[6] = new HockeyPlayer(...stuff);
players[7] = new Golfer(...stuff);
players[8] = new BaseballPlayer(...stuff);
players[9] = new FootBall(...stuff);
players[10] = new HockeyPlayer(...stuff);
players[11] = new Golfer(...stuff);
players[12] = new BaseballPlayer(...stuff);
players[13] = new FootBall(...stuff);
players[14] = new HockeyPlayer(...stuff);
players[15] = new Golfer(...stuff);

2 个答案:

答案 0 :(得分:0)

JDK中已经提供了实现它的实用程序。请查看Arrays文档,特别是deepEquals以验证嵌套数组。

答案 1 :(得分:0)

请参阅Arrays.equals(Object[], Object[])并在您的基类上实现equals()(和hashCode())(我假设所有玩家都从相同的Player类继承。)