如何检查对象不是最后一个对象,如果是最后一个对象如何处理?

How to check that the object isn't the last and how to handle it if it is?

我有一个方法可以循环遍历一袋几何对象并获取特定属性并将当前属性与前一个属性进行比较,如果有的话,目的是存储最高属性然后将其分配给另一个几何.

我刚刚意识到,在某个时刻我将到达那个袋子的尽头,我需要我的方法来提醒我它已经到达袋子中的最后一个物体。

如何识别当前对象是包中的最后一个对象?

int getLargestUnassignedWard() {
        Bag lsoaGeoms = centroidsLayer.getGeometries();

        System.out.println();
        System.out.println("Getting Largest Unassigned Wards!");

        int highestOSVI = -1;
        MasonGeometry myCopy = null;

        for (Object o : lsoaGeoms) {
            MasonGeometry masonGeometry = (MasonGeometry) o;
            int id = masonGeometry.getIntegerAttribute("ID");
            String lsoaID = masonGeometry.getStringAttribute("LSOA_NAME");
            int tempOSVI = masonGeometry.getIntegerAttribute("L_GL_OSVI_");
            Point highestWard = masonGeometry.geometry.getCentroid();
            System.out.println(lsoaID + " - OSVI rating: " + tempOSVI + ", ID: " + id);
            if (assignedWards.contains(id))
                continue;

            // tempOSVI = the attribute in the "L_GL_OSVI_" column - ints
            if (tempOSVI > highestOSVI) { // if temp is higher than highest
                highestOSVI = tempOSVI; // update highest to temp
                myCopy = masonGeometry; // update myCopy, which is a POLYGON
            }
        }

        if (myCopy == null) {
            System.out.println("ALERT: LSOA Baselayer is null!");
            return -1; // no ID to find if myCopy is null, so just return a fake value
        }

        int id = myCopy.getIntegerAttribute("ID"); // Here, id changes to the highestOSVI
        assignedWards.add(id); // add ID to the "assignedWards" ArrayList
        System.out.println("Highest OSVI Raiting is: " + myCopy.getIntegerAttribute("L_GL_OSVI_") + " for LSOA ID: "
                + id + " (" + myCopy.getStringAttribute("LSOA_NAME") + ")");
        System.out.println("Current list of Largest Unassigned Wards: " + assignedWards); // Prints out: the ID for the highestOSVI
        System.out.println();
        return myCopy.getIntegerAttribute("ROAD_ID"); // return Road_ID for the chosen LSOA to visit
    }

I've just realised that at some point I am going to reach the end of that Bag and I need my method to alert me that it has reached the last object in the bag.

我看不出有任何理由让您需要知道该内容才能按照您所说的循环执行。

但是如果你确实需要知道在循环内部,你不能使用增强的for循环;你需要直接使用迭代器:

for (Iterator it = lsoaGeoms.iterator(); it.hasNext(); ) {
    MasonGeometry masonGeometry = (MasonGeometry)it.next();
    boolean isLast = !it.hasNext();
    // ...
}

旁注:我强烈建议使用类型参数而不是原始类型和类型转换。例如,lsoaGeoms 将是 Bag<MasonGeometry>,等等