我需要更改包含哈希映射的數組列表中所選索引的鍵和值。我知道要更換鑰匙,您需要先取下要更換的鑰匙,然后放一把新鑰匙。但這并沒有保存刪除的鍵和值的位置。因此,我想遍歷我的哈希映射數組列表,并在一個新的哈希映射中一個一個地創建它們,我可以在其中為我選擇的索引添加一個 if 命令,假設 1,1 在那里它將改變我的索引位置想要更改并復制那些不被編輯的。我不知道如何以及如何復制的正確方法。請注意,我只是 Java 的初學者,正在努力學習。正確執行此操作的方法是什么?我只是嘗試手動更新鍵和值,但它改變了它應該在的位置/索引。import java.util.*;public class sof { static ArrayList<LinkedHashMap<String, String>> table = new ArrayList<LinkedHashMap<String, String>>(); //2d ArrayList public static void main(String args[]) { setMatrix(); print(); System.out.println(); editValue2(); } static void print(){ for(int x = 0; x < table.size();x++){ System.out.println(table.get(x)); } } static String setChar(){ String result = ""; Random random = new Random(); for(int x = 1; x < 4 ; x++){ result += (char)(32 + random.nextInt(95)); } return result; } static void setRow(int x){ LinkedHashMap<String, String> arr = new LinkedHashMap<>(); for(int z=1; z <= x; z++){ String ran = setChar(); String rann = setChar(); arr.put(ran,rann); } table.add(arr); } static void Setmatrix(){ Scanner row = new Scanner(System.in); System.out.println("Enter Row: "); int zz = row.nextInt(); Scanner column = new Scanner(System.in); System.out.println("Enter Column: "); int z = column.nextInt(); for(int x = 0; x <= zz-1; x++){ setRow(z); } }我希望我可以編輯任何給定表中任何索引的鍵和值。鍵也必須是唯一的。
1 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
您可以獲取和設置給定索引的 ArrayList 值,并替換保留 LinkedHashMap 中地圖索引的鍵值,您必須使用新值克隆它。在這種情況下,您走在正確的軌道上。
editValue2 方法的編輯代碼
int col = 0;
LinkedHashMap<String, String> copy = new LinkedHashMap<>();
// you can get the map from arrayList index
LinkedHashMap<String, String> map = table.get( ind1 ); // assuming ind1 is the arrayList index
for ( Map.Entry<String, String> entry : map.entrySet() )
{
// assuming ind2 is the map index
if ( ind2 == col )
{
copy.put( key, value );
}
else
{
copy.put( entry.getKey(), entry.getValue() );
}
col++;
}
table.set( ind1, copy );
添加回答
舉報
0/150
提交
取消