[英]Android how can i get value of ArrayList Hashmap in my baseadapter
[英]How do i get a clone of my hashmap that is in an arraylist
我需要更改包含哈希映射的數組列表中所選索引的鍵和值。 我知道要更換鑰匙,您需要先刪除將要更換的鑰匙並放一個新鑰匙。 但這並不能保存已刪除鍵和值的位置。 因此,我想到了遍歷哈希映射的數組列表,並在新的哈希映射中逐一創建它們,在其中可以為所選索引添加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);
}
}
static void editValue2(){
Scanner sc = new Scanner(System.in);
String edited = sc.nextLine();
System.out.println("Enter Row: ");
int ind1 = sc.nextInt();
System.out.println("Enter Col: ");
int ind2 = sc.nextInt();
System.out.println("Enter Key: ");
String key = sc.nextLine();
System.out.println("Enter Key: ");
String value = sc.nextLine();
int col=0;
int row=0;
LinkedHashMap<String, String> copy = new LinkedHashMap<String, String>();
for (LinkedHashMap<String, String> map : table){
for(Map.Entry<String,String> set1 : map.entrySet()){
int i = 0;
if(ind1==0 && ind2==0){
copy.put(key,value);
copy.putAll(map);
}else{
if(ind1 == row&& ind2==col){
copy.put(key,value);
}
copy.put(set1.getKey(),set1.getValue());
}
col++;
}
row++;
col=0;
}
map.clear();
map.putAll(copy);
copy.clear();
copy=null;
}
}
我希望我可以編輯任何給定表中任何索引的鍵和值。 鍵也必須是唯一的。
您可以獲取並設置給定索引的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 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.