java - 如何在不更改 Set 顺序的情况下在字符串周围添加引号?
问题描述
我正在做一个 Jarvis 的游行(包装)程序,其中我需要返回凸包上的一组点。我得到了正确的分数,例如 [L0, L1, L2] 但它必须是 ["L1", "L2", "L3"]。
将结果添加到集合中时,我使用了 "\"" + temp.point + "\"" 以及 '"' + temp.point + '"',但它们最终都交换了我的最终结果。
public static Set<String> getBoundary (String sectorFile){
Set<String> points = new HashSet<>();
public static Set<String> getBoundary(String sectorFile){
Set<String> points=new HashSet<>();
Set<Point> vals=new HashSet<>();
Vector<Point> hull=new Vector<Point>();
try(Scanner s=new Scanner(new File(sectorFile))){
s.useDelimiter("[\\\\|\\n\\r]+");
while(s.hasNext()){
String point=s.next();
double x=s.nextDouble();
double y=s.nextDouble();
Point xy=new Point(point,x,y);
xy.setPoint(point);
xy.setX(x);
xy.setY(y);
vals.add(xy);
}
Point[]values=new Point[vals.size()];
vals.toArray(values);
int l=0;
for(int i=1;i<vals.size();i++)
if(values[i].x<values[l].x)
l=i;
// Start from leftmost point, keep moving
// counterclockwise until reach the start point
int p=l,q;
do
{
// Add current point to result
hull.add(values[p]);
q=(p+1)%vals.size();
for(int i=0;i<vals.size();i++)
{
if(orientation(values[p],values[i],values[q])==2)
q=i;
}
p=q;
}while(p!=l); // While we don't come to first
// point
for(Point temp:hull)
points.add(temp.point);
}catch(FileNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return points;
}
private static class Point
{
String point;
double x, y;
Point(String point, double x, double y){
this.point = point;
this.x=x;
this.y=y;
}
private void setPoint(String i) {
this.point = i;
}
private void setX (double x) {
this.x = x;
}
private void setY (double y) {
this.y = y;
}
}
预期的
["L0", "L1", "L2"]
实际的
["L2", "L1", "L0"]
解决方案
大误解:集合没有顺序。您根本不能依靠 HashSet 以相同的“顺序”为您提供元素。
如果有的话,您可以使用 LinkedHashSet (您按插入顺序接收元素)。另一种选择是对所有元素进行隐式排序的 TreeSet。如果这两个选项不能满足您的要求,那么您应该考虑使用完全不同的容器结构。
另请注意:要在 HashSet 中合理使用对象,它们的类应该 @Overrideequals()
和(例如,hashCode()
请参见此处)。您的积分课程没有,这迟早会导致非常意外的行为!
最后:当然,当你有两个集合时,你可以比较它们(就像在集合论中:它们是否有相同的内容,或者有交集,或者根本没有交集)。并假设您的 Point 类有一个合理的equals()
方法,这可能就是您想要的:比较两个集合包含完全相同的点。
推荐阅读
- javascript - 嵌套foreach/forloops,通过JSON循环提取值
- php - 急切加载未正确加载
- amazon-web-services - 如何通过 S3 多对象删除获取有关受影响对象的日志
- r - 安装特定版本的 R 并在 RStudio (Linux Mint) 中打开
- php - Laravel 5.6 存储链接已存在,但尝试从公用文件夹获取文件时出现 404 错误
- reactjs - Redirect after dispatch with history.push
- ruby-on-rails - 如何返回应在每天设定的时间收到约会通知的用户列表
- javascript - 访问动态添加到 XML 对象的节点时遇到问题
- swift - 导入照片时如何保证正确的图像方向?
- android - 如何正确跟踪 Android 应用渠道上的转化?