动机:
我正在创建一个执行以下操作的 android 应用程序。
- 读取输入点(点类型 - 自定义类)。
- 计算最外面的点。
- 以这些点为顶点(凸多边形)绘制多边形(需要从 osmdroid 库输入 GeoPoint 类型)。
问题:
我使算法起作用。但是转换数据类型时出现问题。
输入是一个Point数组(Point是一个自定义类)。
geoPoints = new Point[7];
geoPoints[0] = new Point(new GeoPoint(8.180992, 77.336551));
但是绘制多边形的osmdroid函数需要List
List<GeoPoint> gPoints;
polygon.setPoints(gPoints);
我设法像下面这样在 Point() 构造函数上转换它
public Point(GeoPoint geoPoint) {
this.x = geoPoint.getLatitude();
this.y = geoPoint.getLongitude();
}
但我不知道如何计算返回类型。
所以,当我运行代码时。我收到以下错误。
error: incompatible types: inference variable T has incompatible bounds
equality constraints: GeoPoint
lower bounds: Point
where T is a type-variable:
T extends Object declared in method <T>asList(T...)
调用函数:
private void callingFunction() {
geoPoints = new Point[7];
geoPoints[0] = new Point(new GeoPoint(8.180992, 77.336551));
geoPoints[1] = new Point(new GeoPoint(8.183966, 77.340353));
geoPoints[2] = new Point(new GeoPoint(8.179836, 77.336105));
geoPoints[3] = new Point(new GeoPoint(8.178744, 77.339179));
geoPoints[4] = new Point(new GeoPoint(8.182155, 77.341925));
geoPoints[5] = new Point(new GeoPoint(8.181655, 77.339318));
geoPoints[6] = new Point(new GeoPoint(8.182155, 77.341925));
polygon = new Polygon(); //see note below
polygon.setFillColor(Color.parseColor("#80FFE082"));
polygon.setStrokeColor(Color.parseColor("#FFD54F"));
polygon.setStrokeWidth(5f);
ConvexHull cx = new ConvexHull(geoPoints);
Point C1[]= cx.getConvexHull();
polygon.setPoints(Arrays.asList(C1));
map.getOverlayManager().add(polygon);
map.invalidate();
}
注意:
仅使用 List 或仅使用 Array 是不可能的,因为
polygon.setPoints(geoPoints) //needs List<GeoPoint> in callingFunction
Arrays.sort(points); //requires array of Points in ConvexHull
提供的一切。我怎么解决这个问题?任何形式的帮助都会非常有用。并提前致谢。
最佳答案
我不确定,如果我没听错,但基本上你的问题归结为这样一个事实,即你有一个 Point
对象数组,但需要一个 GeoPoint 列表
对象,对吧?并且Point
和GeoPoint
之间没有关系,所以一个不扩展另一个。
那么为什么不在绘制多边形之前将 Point
对象转换回 GeoPoint
对象呢?
您可以在流中映射类型:
ConvexHull cx = new ConvexHull(geoPoints);
Point C1[] = cx.getConvexHull();
polygon.setPoints(Arrays.stream(C1).map(p -> new GeoPoint(p.getX(), p.getY())).collect(Collectors.toList());
或者使用for
循环:
ConvexHull cx = new ConvexHull(geoPoints);
Point C1[] = cx.getConvexHull();
List<GeoPoint> points = new ArrayList<GeoPoint>(C1.length);
for (int i = 0; i < C1.length; ++i) {
points.add(new GeoPoint(C1[i].getX(), C1[i].getY()));
}
polygon.setPoints(points);
关于java - 数组到列表的转换和类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52000477/