簡體   English   中英

添加到列表后清除 HashMap,在 Java

[英]Clear a HashMap after adding to a List, in Java

如果您能幫助我使用以下 Java 代碼,我將不勝感激:

import java.util.ArrayList;
import java.util.HashMap;


public class JavaApplication2 {
    static ArrayList<HashMap> list_test = new ArrayList<HashMap>();
    static HashMap<String,String> test =new HashMap<>();
   
    public static void main(String[] args) {
        test.put("name", "jhon");
        test.put("lastname", "mckoy");
        list_test.add(test);
        test.clear();
        System.out.println(list_test);
        test.put("name", "Tom");
        test.put("lastname", "Red");
        list_test.add(test);
        
    }
    
}

我有兩個變量,一個叫做 list_test (ArrayList),另一個叫做 test (HashMap <String, String>)。 我的目標是使用以下代碼制作 HashMap 的 ArrayList,但在執行后: test.clear (); 然后 list_test 的內容被刪除。 為什么? 還有其他方法可以制作 HashMap 列表嗎? 哪個?

提前致謝

tl;博士

使用您的代碼,您放入列表中的 map object 與您清除的 map ZA8CFDE6331BD59EB66AC96F8911 相同。 相反,將您的 map 的副本添加到您的列表中。

listOfMapsOfNames.add( Map.copyOf( mapOfNames ) );  // Make an unmodifiable copy of map to be added to list.

復制您的 map

顯然,您希望將 map 的副本添加到列表中。

您的代碼將原始 map 放入列表中。 So now you have two references to the same map: (a) the variable test points to the map, and (b) the first element in the list named list_test points to the very same map object. 如果您使用任一引用來更改地圖的內容,則兩個引用都會看到該更改,因為它們都指向相同的 object

任何一個:

  • 調用Map.copyOf以制作 map 的不可修改副本。 例如: Map.copyOf( oldMap )
  • 將 map 傳遞給另一個Map實現的構造函數,以將條目復制到新的可修改 map。 例如: new HashMap<>( oldMap )

在實用的情況下,您應該考慮養成在參考文獻中使用更通用的超類或接口而不是具體的 class 的習慣。 所以List<Map> list_test而不是ArrayList<HashMap> list_test

您應該參數化List的參數化。 所以List< Map< String, String > >而不是List< Map >

在 Java 標識符上使用更具描述性的名稱將使您的代碼更易於閱讀和調試。 所以像listOfMapsOfNames而不是list_test

示例代碼

這是一些示例代碼。

我將static放在 map 上並列出,因為這無關緊要。

注意兩個調用Map.copyOf( mapOfNames )

List< Map< String, String > > listOfMapsOfNames = new ArrayList<>() ;
Map< String, String > mapOfNames = new HashMap<>() ;

mapOfNames.put( "name", "John" );
mapOfNames.put( "lastname", "McKoy" );
listOfMapsOfNames.add( Map.copyOf( mapOfNames ) );  // Make an unmodifiable copy of map to be added to list.

System.out.println( "map before clear: " + mapOfNames );
mapOfNames.clear();
System.out.println( "map after clear: " + mapOfNames );

mapOfNames.put( "name", "Tom" );
mapOfNames.put( "lastname" , "Red" );
listOfMapsOfNames.add( Map.copyOf( mapOfNames ) );  // Make an unmodifiable copy of map to be added to list.

System.out.println( "map after 2nd add: " + mapOfNames );
System.out.println( "list at the end: " + listOfMapsOfNames );

請參閱在 IdeOne.com 上實時運行的代碼

map before clear: {name=John, lastname=McKoy}
map after clear: {}
map after 2nd add: {name=Tom, lastname=Red}
list at the end: [{lastname=McKoy, name=John}, {lastname=Red, name=Tom}]

record

與您的問題無關,但為了您的信息,使用 class 可能比使用Map跟蹤名字和姓氏更有意義。 現在我們有了更簡單的方法來編寫這樣的 class: records

記錄功能是Java 16中的新功能。 記錄是編寫 class 的簡要方法,其主要目的是透明且不可變地傳遞數據。 編譯器隱式創建構造函數、getter、 equals & hashCodetoString 獎勵:記錄可以在本地聲明,也可以聲明為嵌套的或單獨的。

請注意,您的代碼的以下版本使用record變得更具表現力(並且更短)。

record Person(String firstName , String lastName) {}
List < Person > people = new ArrayList <>();

people.add( new Person( "John" , "McKoy" ) );
people.add( new Person( "Tom" , "Red" ) );

people.toString(): [Person[firstName=John, lastName=McKoy], Person[firstName=Tom, lastName=Red]]

解決方案:

  1. 'test' 的克隆 (HashMap<String,String>)
  2. 從“測試”(HashMap<String,String>)創建新的 Map

這是代碼:

public class ListOfMapJavaApplication2 {
    static ArrayList<HashMap> list_test = new ArrayList<HashMap>();
    static HashMap<String,String> test =new HashMap<>();

    public static void main(String[] args) {
    test.put("name", "jhon");
    test.put("lastname", "mckoy");
    //list_test.add(new HashMap<String,String>(test));
    list_test.add((HashMap<String,String>)test.clone());
    test.clear();
    System.out.println(list_test);
    test.put("name", "Tom");
    test.put("lastname", "Red");
    //list_test.add(new HashMap<String,String>(test));
    list_test.add((HashMap<String,String>)test.clone());

    }
}

這是因為引用調用而發生的,您可以使用 new 關鍵字獲取新引用。

import java.util.ArrayList;
import java.util.HashMap;

public class Main
{
static ArrayList<HashMap> list_test = new ArrayList<HashMap>();
    static HashMap<String,String> test =new HashMap<>();
   
    public static void main(String[] args) {
        test.put("name", "jhon");
        test.put("lastname", "mckoy");
        list_test.add(test);
        test = new HashMap<>();
        System.out.println(list_test);
        test.put("name", "Tom");
        test.put("lastname", "Red");
        list_test.add(test);
        System.out.println(list_test);
    }
}

暫無
暫無

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

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