我很難考慮如何在長度為 5 的字串陣列最初為空時實作檢查重復項。在陣列中添加一個元素之前,我必須先檢查它是否已經存在于陣列中但是因為陣列最初是空的(這意味著五個元素都是空的)它會提示錯誤,我認為那是因為我正在嘗試將元素(我試圖添加到陣列中)與 null 進行比較。
我想要做的是檢查陣列的長度是否小于限制,檢查我要添加的元素在陣列中是否沒有重復。如果它沒有重復,那么我將它添加到陣列中,如果它有重復,那么我不會添加它,然后我將列印一條提示訊息。
我正在開發一個包含多個類的專案,這是我的代碼片段:
public class Collections {
Guardian[] guardians;
int count;
final static int MAX_GUARDIANS = 5;
public Collection () {
guardians = new Guardian[Collection.MAX_GUARDIANS];
}
public void addGuardians (Guardian guardian) {
if (this.count < MAX_GUARDIANS) {
for (int i = 0; i < guardians.length; i ) {
if (guardians[i].equals(guardian)) {
System.out.println("The guardian is already in the list!\n");
} else {
this.guardians[this.count ] = guardian;
System.out.println("Guardian " guardian.getName() " was added to the list!");
}
}
} else {
System.out.println("Maximum number of guardians in the list has been reached!\n");
}
}
}
是否可以比較我打算添加到 null 的元素?
uj5u.com熱心網友回復:
您可以嘗試使用 aHashSet<String>來跟蹤重復項,并跟蹤陣列中的唯一字串。
宣告一個哈希集:
HashSet<String> set = new HashSet<String>();
// Or:
// Set<String> set = new HashSet<String>();
檢查一個字串是否在一個集合中:
if(set.contains("Hello")) {
// String is in the set
}
將字串添加到集合中:
set.add("Hello");
uj5u.com熱心網友回復:
使用串列而不是陣列來檢查它是否已經包含該監護人。
public class Collections {
List<Guardian> guardians;
int count;
final static int MAX_GUARDIANS = 5;
public Collections () {
guardians = new LinkedList<>();
}
public void addGuardians (Guardian guardian) {
if (guardians.size() >= MAX_GUARDIANS) {
System.out.println("Maximum number of guardians in the list has been reached!\n");
return;
}
if (guardians.contains(guardian)) {
System.out.println("The guardian is already in the list!\n");
} else {
guardians.add(guardian);
System.out.println("Guardian " guardian.getName() " was added to the list!");
}
}
}
uj5u.com熱心網友回復:
因此,當您要搜索重復項時,您必須先搜索整個陣列。然后如果沒有重復,在for回圈之后添加一個元素。
for (int i = 0; i < count; i ) {
if (guardians[i].equals(guardian)) {
System.out.println("The guardian is already in the list!\n");
return; // <-- add this to EXIT when find a match
}
}
// now that you've searched the whole list,
// you can add a new element
guardians[count ] = guardian;
System.out.println("Guardian " guardian.getName() " was added to the list!");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526194.html
標籤:爪哇数组细绳空指针异常
