我有一个Road对象的ArrayList,它有一些atttributes,例如number,start_latitude,start_longitude,end_latitude,end_longitude。现在我想要返回半径为500米的道路,以获得给定的纬度值。所以我尝试了
ArrayList<Roads> RoadList=new ArrayList<Roads>();
//I added all the road objects like below
RoadList.setNumber(01);
RoadList.setStartLatitude(1.24);
RoadList.setStartLongitude(102.3);
RoadList.setEndLatitude();
RoadList.setEndLongitude();
//Then I compute the distance between the end of road and given lat lon and also distance between start of road from give lat lon values and if the distance is below 500 I pick the road object.
given latitude=1.2;
given logitude=103.8
public ArrayList<Integer> getRoads(){
ArrayList<Integer> roads=new ArrayList<Integer>();
for(int i=0; i<RoadList.size();i++){
double x= Math.pow( Math.pow(RoadList.get(i).getStartLatitude()-given latitude,2)+Math.pow(RoadList.get(i).getStartLongitude()-given longitude,2),0.5);
double y= Math.pow( Math.pow(RoadList.get(i).getEndLatitude()-given latitude,2)+Math.pow(RoadList.get(i).getEndLongitude()-given longitude,2),0.5);
if(x <500 || y<500){
roads.add(RoadList.get(i).getNumber());
}
}
return roads;
}
由于我的ArrayList有点大,需要一段时间。所以有什么有效的方法吗?
答案 0 :(得分:3)
如何转换这两行
double x= Math.pow( Math.pow(RoadList.get(i).getStartLatitude()-given latitude,2)+Math.pow(RoadList.get(i).getStartLongitude()-given longitude,2),0.5);
double y= Math.pow( Math.pow(RoadList.get(i).getEndLatitude()-given latitude,2)+Math.pow(RoadList.get(i).getEndLongitude()-given longitude,2),0.5);
这样的事情
double start_x1 = RoadList.get(i).getStartLatitude()-given latitude;
double start_x2 = RoadList.get(i).getStartLongitude()-given longitude;
start_x1 *= start_x1;
start_x2 *= start_x2;
double end_x1 = RoadList.get(i).getEndLatitude()-given latitude;
double end_x2 = RoadList.get(i).getEndLongitude()-given longitude;
end_x1 *= end_x1;
end_x2 *= end_x2;
double x = Math.sqrt(start_x1 + start_x2);
double y = Math.sqrt(end_x1 + end_x2);
因此,不是使用Math.pow进行平方,而是可以在O(1)中执行此计算,可能会提高我们的速度。
我不是很确定,但你可以尝试一下,让我知道。
希望这有帮助!
答案 1 :(得分:3)