簡體   English   中英

在Java中處理ArrayList中的相等性

[英]Dealing with equality in an ArrayList in java

說我有這段代碼:

for(int i = 0; i < accounts.size(); i++) {
    if(UserID.equals(accounts.get(i).getUserID())) {
        if(accounts.contains(accounts.get(i))) {
            if(UserPass.equals(accounts.get(i).getPassword())) {
                System.out.println("True");
            }
        } else {
            typePhrase("unrecognised userID: '" + UserID + "'");
        }
    } else {
        typePhrase("unrecognised userID: '" + UserID + "'");
    }
}

它通過一個充滿對象的arrayList,該對象具有一個ID和一個密碼。 我從用戶那里得到了兩個輸入,一個是用戶ID,另一個是密碼。 我想要的是讓它遍歷保存在該arrayList中的每個可能的對象,如果找到匹配項,則將true打印到控制台中,我遇到的問題是,如果您鍵入錯誤的內容,則會打印出來一條消息,表明無法對arrayList中的每個對象進行識別。 如果在右邊鍵入一個,它還會為arrayList -1中存在的每個對象輸出消息。 你建議我做什么?

用戶類別:

public class User {
    String userID;
    String password;

    public User(String ID, String Pass) {
        userID = ID;
        password = Pass;
    }

    public String getUserID() {
        return userID;
    }

    public String getPassword() {
        return password;
    }
}

編輯:

ArrayList<User> accounts = new ArrayList<User>();

您應該在User類中實現equals方法:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    User user = (User) o;

    if (!getUserID().equals(user.getUserID())) return false;
    return getPassword().equals(user.getPassword());

}

然后,您可以使用鍵入的信息創建一個新用戶,只需檢查列表中是否包含該用戶:

User user = new User("typedUserId", "typedPassword");
System.out.println(accounts.contains(user));

我看到這是新程序員經常犯的錯誤。 您正在搜索列表以查看是否有任何元素符合某些條件(例如,ID和密碼匹配)。 如果沒有任何元素滿足條件,則執行指示錯誤的操作。

但是,直到遍歷列表的每個元素,您都無法確定是否有錯誤。 因此,在循環完全完成 之后必須出現任何錯誤消息,對嗎? 不在循環中間。 但是,您已將“無法識別的”消息放入循環的中間。 那行不通。

有幾種常見的慣用法可以解決此問題,但這是一個簡單的慣用法:

boolean found = false;
for (whatever-your-loop-should-look-like) {
     if (the-current-element-meets-the-condition) {
         found = true;
         break;
     }
}
if (!found) {
     whatever-action-you-take-when-it-isn't-found;
}

刪除此檢查...在遍歷那些對象以檢查當前對象是否在其來源的對象列表內時,這沒有任何意義。

if(accounts.contains(accounts.get(i))) {

否則,當用戶ID和密碼匹配時,您的代碼將輸出True(但將繼續檢查列表的其余部分)。 否則,將打印其他信息。 如果要在打印True時停止循環,請在此處放置break

但是,為了解決該問題,未實現User.equals() ,因此使用了比較對象的默認方式(通過hashcode方法)。

您應該實現它以比較用戶ID和密碼的相等性。

不知道在這里實現equals()是否是明智的選擇。 但是,這不是您想做的那么簡單嗎:

boolean found = false;
for (User u : accounts) {
  if (userId.equals(u.getUserId()) && userPass.equals(u.getPassword()) {
    found = true;
    break;
  }
}

如果您使用Java 8+,甚至可以使用流API。

accounts.stream().anyMatch(u -> userId.equals(u.getUserId()) 
                              && userPass.equals(u.getPassword());

可以使用布爾變量來確定是否找到匹配項,而不是打印true或not found。

boolean found = false
for each value in the array
   if it's a match set found to true
   if it's not a match do nothing, i.e. continue to next position
if (found) print "true" else print "not found"

如果找到匹配項,也可以跳出循環,而無需繼續檢查其他匹配項。

boolean found = true
for each value in the array
   if it's a match set found to true and break out of loop
   if it's not a match do nothing, i.e. continue to next position
if (found) print "true" else print "not found"

更好的是,您可以將代碼移至返回布爾值並擺脫變量的方法。

boolean isThereAMatch() {
    for each value in the array
       if it's a match set return true
       if it's not a match do nothing, i.e. continue to next position
    return false
}

您可以調用它來檢查要打印的內容。

if (isThereAMatch()) print "true" else print "not found"

您正在努力使用List contains()還是使用簡單的for循環。 可以通過兩種方式完成,下面是這兩種代碼的示例。 為了使用contains,您必須向User添加一個equals()覆蓋的方法。

List.contains()文檔

如果此列表包含指定的元素,則返回true。 更正式地講,當且僅當此列表包含至少一個元素(e == null?e == null:o.equals(e))時,返回true。

與For循環

import java.util.*;

public class TestMain {
    public static void main (String[] args) {
        List<User> accounts = new ArrayList<User>();
        User user1 = new User("test", "test");
        User user2 = new User("test1", "test1");

        accounts.add(user1);
        accounts.add(user2);

        String userId = "test";
        String userPass = "test1";

        boolean matchFound = false;

        for(User account : accounts) {
            if(userId.equals(account.getUserID()) && userPass.equals(account.getPassword())) {
                System.out.println("True");
                matchFound = true;
            }
        }

        if(!matchFound) {
            System.err.println("unrecognised userID: '" + userId + "'");
        }
    }
}

class User {
    String userID;
    String password;

    public User(String ID, String Pass) {
        userID = ID;
        password = Pass;
    }

    public String getUserID() {
        return userID;
    }

    public String getPassword() {
        return password;
    }
}

與contains()和equals()

import java.util.*;

public class TestMain2 {
    public static void main (String[] args) {
        List<User> accounts = new ArrayList<User>();
        User user1 = new User("test", "test");
        User user2 = new User("test1", "test1");

        accounts.add(user1);
        accounts.add(user2);

        String userId = "test1";
        String userPass = "test1";

        boolean matchFound = accounts.contains(new User(userId, userPass));

        if(!matchFound) {
            System.err.println("unrecognised userID: '" + userId + "'");
        } else {
            System.out.println("True");
        }
    }
}

class User {
    String userID;
    String password;

    public User(String ID, String Pass) {
        userID = ID;
        password = Pass;
    }

    public String getUserID() {
        return userID;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public boolean equals(Object user) {
        boolean isEqual = false;

        if(user != null && user instanceof User) {
            User userType = (User)user;
            boolean userIdMatched = (userID == null) ? userType.getUserID() == null : userID.equals(userType.getUserID());
            boolean passwordMatched = (password == null) ? userType.getPassword() == null : password.equals(userType.getPassword());

            isEqual =  userIdMatched && passwordMatched;
        }


        return isEqual;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM