开发者

Do anyone know how to sort stack using array.sort()? I just want to print the ordered list of points by their x coordinates. Any idea?

import java.util.*;

public class Point2D
{
  private double x;
  private double y;

  public Point2D(double x, double y)
  {
    this.x = x;
    this.y = y;
  }

  private double Euclidean()
  {
    double Distance = Math.sqrt((x * x) + (y * y));
    return Distance;
  }

  public String toString()
  {
    return "x: " + x + ", y: " + y;
  }

  public static class YOrder implements Comparator<Point2D>
  {    
    public int compare(Point2D self, Point2D other)
    {
      if (self.y > other.y)
        return 1;

      if (self.y < other.y)
        return -1;

      else
        return 0;
    }
  }

  public static void main(String[] args)
  {
    Stack<Point2D> stack = new Stack<Point2D>();

    while (!StdIn.isEmpty())
开发者_如何转开发    {
      double x = StdIn.readDouble();
      double y = StdIn.readDouble();
      stack.push(new Point2D(x,y));
    }

    Arrays.sort(stack);
  }
}

This is for a class and I'm not allowed to use Collections or ArrayList.


Arrays.sort(stack);

should be

 Collections.sort(stack, new YOrder());//pass comparator


Sure, you need to supply a comparator.

Arrays.sort(stack.toArray(new Point2D[0](), new Comparator(){
    public int compare(Point2D a, Point2D b)
        { return a.x-b.x; }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜