0

我有两个搜索循环来执行不同的操作,但我对它看起来的重复性不满意。

用于删除项目的第一种方法如下:

public void RemovePlayer(int theID){
    boolean matchFound = false;

    if (playerObjects.size() != 0){
        for (int i = 0; i < playerObjects.size(); i++){
            Person playerToRemove = (Person) playerObjects.get(i);
            if (playerToRemove.getID() == theID){
                playerObjects.remove(i);
                System.out.println("Player with ID # " + theID + " removed");
                matchFound = true;
                // As ID is unique, once a player is found it is unnecessary to continue looping
                break;
            }

            // If matchFound is never set to true then show appropriate error
            if (matchFound == false) {
                System.out.println("Player with ID # " + theID + " not found");
            }
        }
    }
    else {
        System.out.println("No players have been added.");    
    }
}

第二种方法,本质上是相同的代码,但如果找到匹配项则执行不同的操作,如下所示:

public void RetrievePlayer(int theID){
    boolean matchFound = false;

    if (playerObjects.size() != 0){
        for (int i = 0; i < playerObjects.size(); i++){
            Person playerToRetrieve = (Person) playerObjects.get(i);
            if (playerToRetrieve.getID() == theID){
                System.out.println("PLAYER FOUND:");
                playerToRetrieve.GetDetails();
                matchFound = true;
                break;
            }

            // If matchFound is never set to true then show appropriate error
            if (matchFound == false) {
                System.out.println("Player with ID # " + theID + " not found");
            }
        }
    } else {
        System.out.println("No players have been added.");    
    }
}

我该如何重构呢?

4

3 回答 3

3

返回播放器索引的方法“FindPlayer”怎么样i?RemovePlayer 和 RetrievePlayer 将是:

public void RemovePlayer(int theID){
    int playerId = FindPlayer(theID);
    if (playerId >= 0) {
        playerObjects.remove(playerId);
    }
}

public void RetrievePlayer(int theID){
    int playerId = FindPlayer(theID);
    if (playerId >= 0) {
        Person player = (Person) playerObjects.get(playerId);
        player.getDetails();
    }
}

“FindPlayer”方法有点像这样:

protected int FindPlayer(int theID){
    if (playerObjects.size() != 0){
        for (int i = 0; i < playerObjects.size(); i++){
            Person player = (Person) playerObjects.get(i);
            if (player.getID() == theID){
                return i;
            }
        }

        System.out.println("Player with ID # " + theID + " not found");
    } else {
        System.out.println("No players have been added.");    
    }

    return -1;
}
于 2012-05-01T07:33:27.953 回答
1

将播放器放在一个Map<Integer,Player>. 然后使用 Map 的基本方法 ( put, remove) 而不是循环遍历列表。

于 2012-05-01T08:14:25.377 回答
0

如果你分开,你可以有一个find返回 a的方法Player和一个remove将玩家作为参数的方法。我更喜欢这个而不是返回索引,因为索引可能是临时的(例如,如果其他人添加到列表中,索引可能会失效)。

您可以做更多事情(可能是带有谓词findAll的方法或filter方法),但在您有理由这样做之前我不会看这些(您不需要它)

于 2012-05-01T07:34:10.443 回答