[英]How to remove duplicates from a parallel array in Java?
因此,我開始學習Java,並想知道如何將字符串和int類型的並行數組從源數組中存儲一次。 例如,我有兩個彼此平行的數組,一個數組將電話號碼存儲為字符串,另一個數組將通話時間存儲為從每個電話號碼獲得的整數。
String[] phoneNumbers;
phoneNumbers = new String[100];
int[] callDurations = new int[phoneNumbers.length];
int size = 0;
phoneNumbers[0] = "888-555-0000";
callDurations[0] = 10;
phoneNumbers[1] = "888-555-1234";
callDurations[1] = 26;
phoneNumbers[2] = "888-555-0000";
callDurations[2] = 90;
phoneNumbers[3] = "888-678-8766";
callDurations[3] = 28;
size = 4;
我編寫了一種方法來查找特定電話號碼的詳細信息,例如特定呼叫的持續時間“ 888-555-1234”。這是該方法及其調用方式:
public static void findAllCalls(String[] phoneNumbers, int[] callDurations, int size, String targetNumber) {
int match;
System.out.println("Calls from " + targetNumber + ":");
match = find(phoneNumbers, size, 0, targetNumber);
while (match >= 0) {
System.out.println(phoneNumbers[match] + " duration: " + callDurations[match] + "s");
match = find(phoneNumbers, size, match + 1, targetNumber);
}
}
System.out.println("\n\nAll calls from number: ");
findAllCalls(phoneNumbers, callDurations, size, "888-555-1234");
此代碼的輸出是:
All calls from number:
Calls from 888-555-1234:
888-555-1234 duration: 26s
888-555-1234 duration: 28s
Process finished with exit code 0
而我想獲得的輸出是:
All calls from number:
Calls from 888-555-1234:
888-555-1234 duration: 54s
Process finished with exit code 0
(26s + 28s)
在Java中如何確保並行數組中沒有重復存儲並獲取每個電話號碼的總持續時間,而不是將它們分別存儲在數組中?
問題是:“在Java中如何確保並行數組中沒有重復存儲,並獲得每個電話號碼的總持續時間,而不是將它們分別存儲在數組中?”
答案是:沒有(便宜的)方法。
請改用哈希圖。 看看java.utils.HashMap
。 哈希映射是用於存儲與特定鍵關聯的(任何類型的)值的概念。 在您的情況下,值將是持續時間,鍵將是您的電話號碼。 因此,您應該在此處使用String
- Integer
哈希映射。
在插入時執行以下操作:
稍后,您可以有效地執行查找。
映射是將鍵映射到值的對象
在您的情況下,您希望電話號碼(存儲在String
)對應於通話時間( int
)。 因此,您需要按以下方式聲明HashMap
( 請注意,您無法實例化Map
,它是一個接口):
Map<String, Integer> callRecords = new HashMap<String, Integer>();
這是一個更好的版本,因為您不再需要跟蹤兩個不同的陣列。 現在,代替
phoneNumbers[0] = "888-555-0000";
callDurations[0] = 10;
你可以寫:
callRecords.put("888-555-0000", 10);
如之前的答案中所述,您可以使用地圖-避免在phoneNumber和callDuration中重復 ( Java代碼可防止HashMap / HashTable中的<Key,Value>對重復 )。
或者,如果您想堅持使用String實現,則可以在findAllCalls()方法中更改邏輯。
public static void findAllCalls(String[] phoneNumbers, int[] callDurations, int size, String targetNumber)
{
int match;
System.out.println("Calls from " + targetNumber + ":");
//match = find(phoneNumbers, size, 0, targetNumber);
int i = 0, duration = 0;
while (i<size)
{
if(phoneNumbers[i].equals(targetNumber))
duration+=callDurations[i];
i++;
//System.out.println(phoneNumbers[match] + " duration: " + callDurations[match] + "s");
//match = find(phoneNumbers, size, match + 1, targetNumber);
}
System.out.println(targetNumber+" duration : "+duration+"s");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.