簡體   English   中英

如何將字符串類型的數組值存儲到HashMap對象中

[英]How to store String type of array values in to HashMap object

當我嘗試將String數組值存儲到hashmap時,它將顯示null value.please提供任何解決方案。謝謝提前

                String temp;
                String[] line=new String[15];
                Map<String, String> map=new HashMap<String, String>();

                InputStream stream=new FileInputStream(path);
BufferedReader reader =new BufferedReader(new InputStreamReader(stream));
                while((temp = reader.readLine()) != null)
                {
                    for(int j=0; j<line.length ;j++)
                    {   
                        line[j]=reader.readLine();

                        String fname=line[0];
                        String lname=line[1];
                        String mobile=line[2];
                        String gender=line[3];

                    //Store array string to map
                        map.put("fname",fname);

                    //retrive map object    
                       System.out.println(map.get(fname));

                System.out.println(fname);//showing null value in console

                System.out.println(lname);//array shows values
                System.out.println(mobile);//array shows values

                    }

您試圖按值獲取地圖值(變量fname)

 System.out.println("map.get(fname) = "+map.get(fname));

但你應該使用map.get(key) ,你的密鑰是“fname”(作為字符串)而不是fname(作為變量)

解決方案是

System.out.println("map.get(fname) = "+map.get("fname"));

並且對於FileInputStream嘗試使用file而不是path:

 File file = new File("C:/*****");
 InputStream stream=new FileInputStream(file);

暫無
暫無

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

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