2015-09-07 39 views
-1

我有一個小問題。我從多個Beacon獲取數據,並將其放入一個arrayList中。現在我想要最近的一個應該返回。獲得對象的最大值

ArrayList<Beacon> arrayList = new ArrayList<Beacon>(); 
String beaconName; 

public void addToBeaconInfo(Beacon beacon) { 

    boolean beaconAlreadyInList = false; 
    //arrayList.add(beacon); 
    beaconName = "" + beacon.getId2() + "" + beacon.getId3(); 
    //Log.i("BeaconInfo","addBeacon_beaconName: "+beaconName + " distance" + beacon.getDistance()); 

    int i; 
    for(i = 0; i < arrayList.size(); i++){ 
     Beacon tempBeacon = arrayList.get(i); 

     if(tempBeacon.getId2().equals(beacon.getId2())){ 
      beaconAlreadyInList = true; 
      arrayList.remove(beacon); 

      Log.i("BeaconInfo", "addBeacon_tempBeacon: " + beacon.getId3() + " distance: " + beacon.getDistance()); 
      break; 
     } 
    } 
    if(beaconAlreadyInList == false){ 
     arrayList.add(beacon); 
     Log.i("arrayList","" + beacon.getDistance() + " " + beacon.getBluetoothName()); 
     double maxDistance = beacon.getDistance(); 
     //double a = Collections.max(maxDistance); 
     //Log.i("maxDistance","" + Math.max()); 
    } 
} 
+0

嘗試使用'的https:// developer.android.com /參考/安卓/支持/ V7/UTIL/SortedList.html' – Panther

回答

0
Beacon nearest = null; 
double distance = Double.MAX_VALUE; 
for (Beacon beacon: arrayList){ 
    double maxDistance = beacon.getDistance(); 
    if (maxDistance < distance) { 
    distance = maxDistance; 
    nearest = beacon; 
    } 
} 
+0

感謝您快速的要求,但這隻會有兩個工作信標。在我的情況下,我有一個可變數量的信標,我想按他的距離排序。 – ebuddy

+0

您在問題中寫道您需要最近的燈塔。如果你需要排序只是使用[排序算法](https://en.wikipedia.org/wiki/Sorting_algorithm) –

+0

這是真的,它可以是;)但更多的只是兩個信標。 – ebuddy