我的作业要求我使用java.util.TreeSet
使用二叉搜索树实现一个点集API类。 PointSet API大纲如下所示:
public class PointSET {
public PointSET() {} // construct an empty set of points
public boolean isEmpty() {} // is the set empty?
public int size() {} // number of points in the set
public void insert(Point2D p) {} // add the point p to the set (if it is not already in the set)
public boolean contains(Point2D p) {} // does the set contain the point p?
public Collection<Point2D> range(RectHV rect) {} // all points in the set that are inside the rectangle
public Point2D nearest(Point2D p) {} // a nearest neighbor in the set to p; null if set is empty
}
Point2
对象是一个简单的点,带有x和y坐标以及一些其他方法来计算两点之间的距离。RectHV
对象表示在范围内搜索矩形内点的矩形。我想我不确定如何在BST中实现此API类。我们在课堂上学到了BST,但只是广义上讲;它们是什么以及后期/预购/顺序搜索它们的方式。
我也很困惑API本身是什么。是什么使这个API成为不 API的东西?
“实施”API涉及什么?以及如何使用java.util.TreeSet
来执行此操作?
我将不胜感激。
答案 0 :(得分:0)
您可以将应用程序编程接口(API)视为合同。它指定了对象彼此交互的方式。
为了说明API是什么,请考虑接口Dictionary
:
public interface Dictionary {
List<String> loadWords();
}
接口Dictionary
建立所有字典实现必须遵循的合同(API)。字典实现的两个例子可能是:
public class TextFileDictionary implements Dictionary {
public List<String> loadWords() {
// load words from a text file and return them
return words;
}
}
public class DatabaseDictionary implements Dictionary {
public List<String> loadWords() {
// load words from database and return them
return words;
}
}
我们现在以你的PointSET
课程为例。如您所见,它有许多方法来定义PointSET
类型对象的行为。
public class PointSET {
// private ... <- your data structure goes here.
public PointSET() {}
public boolean isEmpty() {}
public int size() {}
public void insert(Point2D p) {}
public boolean contains(Point2D p) {}
public Collection<Point2D> range(RectHV rect) {}
public Point2D nearest(Point2D p) {}
}
正如@alexBrand所指出的,一个很好的起点是定义你的数据结构。在您的情况下,明显的选择是BST。然后,为了与提供的API保持一致,您将不得不操纵数据结构来实现PointSET
的预期行为。