首页 > 解决方案 > 如何在不更改 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"]

标签: java

解决方案


大误解:集合没有顺序。您根本不能依靠 HashSet 以相同的“顺序”为您提供元素

如果有的话,您可以使用 LinkedHashSet (您按插入顺序接收元素)。另一种选择是对所有元素进行隐式排序的 TreeSet。如果这两个选项不能满足您的要求,那么您应该考虑使用完全不同的容器结构。

另请注意:要在 HashSet 中合理使用对象,它们的类应该 @Overrideequals()和(例如,hashCode()请参见此处)。您的积分课程没有,这迟早会导致非常意外的行为!

最后:当然,当你有两个集合时,你可以比较它们(就像在集合论中:它们是否有相同的内容,或者有交集,或者根本没有交集)。并假设您的 Point 类有一个合理的equals()方法,这可能就是您想要的:比较两个集合包含完全相同的点。


推荐阅读