列表包含不起作用

时间:2016-02-18 18:29:54

标签: android list contains

我试图找出用户在Google地图上推送的Polyline。但我的下面的代码没有返回我期望的内容:

String k999 = "lat/lng";

List Klick = polyline.getPoints();

System.out.println("The list contains one " + Klick.contains(k999));
System.out.println("The list contains two " + Klick.contains("52.3524921"));
System.out.println("The list contains three " + "[lat/lng:".contains("[lat/lng:"));
System.out.println("Str-Str: " + Klick.contains(Klick));
System.out.println("equals: " + Klick.equals(Klick));
System.out.println("List: " + Klick);

输出:

The list contains one false
The list contains two false
The list contains three true
Str-Str: false
equals: true
List: [lat/lng: (52.3524987,7.709607499999999), lat/lng: (52.3524921,7.7098328).........

为什么我的contains代码不起作用?

2 个答案:

答案 0 :(得分:0)

您的Klick List对象实际上是LatLng对象的列表: https://developers.google.com/android/reference/com/google/android/gms/maps/model/Polyline.html#getPoints()

https://developers.google.com/android/reference/com/google/android/gms/maps/model/LatLng.html#toString()

当您使用System.out.println(Klick)时,实际上是在每个LatLng对象上调用toString()方法。如果查看LatLng类,可以看到toString方法如下所示:

public String toString() {
    return "lat/lng: (" + this.latitude + "," + this.longitude + ")";
}

当您对List执行.contains()操作时,每个对象都会调用其.equals()方法。对于LatLng,该方法是:

public boolean equals(Object o) {
    if(this == o) {
        return true;
    } else if(!(o instanceof LatLng)) {
        return false;
    } else {
        LatLng var2 = (LatLng)o;
        return Double.doubleToLongBits(this.latitude) == Double.doubleToLongBits(var2.latitude) && Double.doubleToLongBits(this.longitude) == Double.doubleToLongBits(var2.longitude);
    }
}

所以,如果你想弄清楚你的折线是什么,你可以这样做:

for(int i = 0, size = Klist.size(); i < size; i++) {
    LatLng currentLatLng = (LatLng)Klist.get(i);
    // do something with your LatLng
    double latitude = currentLatLng.latitude;
    double longitude = currentLatLng.longitude;
    System.out.printf("Latitude is %f. Longitude is %f", latitude, longitude);
}

希望这有帮助!

答案 1 :(得分:0)

是的,经过数小时的编码后运行;-) 非常感谢你!

List Klick = polyline.getPoints();

for(int i = 0, size = Klick.size(); i < size; i++) {
    LatLng currentLatLng = (LatLng) Klick.get(i);
    String KL = Klick.toString();

    // do something with your LatLng
    double latitude1 = currentLatLng.latitude;
    double longitude1 = currentLatLng.longitude;
    System.out.printf("\nLatitude: "+KL);
    System.out.printf("\ncontains: "+KL.contains("52.3524987"));

输出:

Latitude: [lat/lng: (52.3524987,7.709607499999999), lat/lng: (52.3524921,7.7098328), lat/lng: (52.3534915,7.710031300000001).......
contains: true