首頁  >  文章  >  Java  >  如何在 Java 映射中儲存單一鍵的多個字串值?

如何在 Java 映射中儲存單一鍵的多個字串值?

Susan Sarandon
Susan Sarandon原創
2024-10-28 02:31:31289瀏覽

How to Store Multiple String Values for a Single Key in a Java Map?

在Map 中儲存多個字串

在Java 中,您可能會遇到一種場景,您需要在Map 中為某個鍵儲存多個字串值。然而,Java 的標準 Map 介面不支援為單一鍵儲存多個值。

問題:

是否可以設定兩個以上的鍵值對地圖?例如,您可以建立一個如下所示的Map 結構:

<code class="java">Map<String,String,String,String></code>

其中每個鍵(「數字」)與多個值(「姓名」、「地址」、「電話」)關聯,這些值是一起顯示嗎?

答案:

這個問題的解決方案是避免使用多個鍵,而是使用一個物件來保存各個字串值。考慮建立一個封裝姓名、地址和電話號碼的ContactInformation 類別:

<code class="java">public class ContactInformation {
    private String name;
    private String address;
    private String phone;

    // Constructor and getters/setters
}</code>

然後您可以使用此物件作為Map 中的值:

<code class="java">Map<String, ContactInformation> contacts = new HashMap<>();

ContactInformation contact = new ContactInformation();
contact.setName("John Doe");
contact.setAddress("123 Main Street");
contact.setPhone("(555) 123-4567");

contacts.put("number", contact);</code>

當您需要時要訪問這些值,您可以從地圖中檢索ContactInformation 物件並存取其屬性:

<code class="java">ContactInformation contact = contacts.get("number");
String name = contact.getName();
String address = contact.getAddress();
String phone = contact.getPhone();</code>

透過使用物件封裝多個字串值,您可以避免Java 的Map 介面的限制並有效地儲存並檢索相關資訊。

以上是如何在 Java 映射中儲存單一鍵的多個字串值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn