【发布时间】:2020-02-22 11:37:34
【问题描述】:
目前我有一个方法重载了以下方法:
public boolean isHorizontalOrVertical(Point firstPoint, Point secondPoint) {
return firstPoint.getFirstComponent() == secondPoint.getFirstComponent()
|| firstPoint.getSecondComponent() == secondPoint.getSecondComponent();
}
public boolean isHorizontalOrVertical(List<Point> points) {
if (points == null || points.size() < 2) {
throw new IllegalArgumentException("invalid number of points");
}
Point start = points.get(0);
return points.stream()
.allMatch(p -> isHorizontalOrVertical(start, p));
}
需要该方法来检查两个或三个点是否相互垂直/水平。在三个点的情况下,它只需要检查最后两个点是否与起点水平/垂直。
有没有人知道我怎样才能把这一切都集中在一种方法中?
【问题讨论】:
-
你可以使用可变参数,你可以有一个接受列表的函数?
-
是的,但是具有所需功能的一种方法看起来如何?
-
您为什么要这样做?我将重命名您的第二种方法,以便您可以阅读它检查列表中的 all 点是水平的还是垂直的。类似:
allPointsAreHorizontalOrVertical -
要求调用者将两点作为列表传递有什么好处?如果您不想在公共 API 中公开两点版本,只需将该方法设为私有即可。
标签: java overloading