I am getting this strange output in HashMap.
I have two ArrayList<String> one containing the key and another containing value.
My HashMap<String,String> will store only string as key and value pair. But key itself is getting stored in value. I have checked my value arraylist, it’s printing the value. But during putting it’s setting it as key itself.
Code snippet is:
public HashMap<String,String> getLstBarring()
{
ArrayList<String> temparrLst=setPreParameters(fetchPreDetails, 1);
System.out.println("KEY" + temparrLst);
ArrayList<String> tempArrLstId=setPreParameters(fetchPreDetails, 14);
System.out.println("VALUE" +tempArrLstId);
int length=tempArrLstId.size();
for(int index=0;index<length;index++)
{
System.out.println("VALUE IN KEY" + temparrLst.get(index));
System.out.println("VALUE IN VALUE" + tempArrLstId.get(index));
this.lstBarring.put(temparrLst.get(index), tempArrLstId.get(index));
}
System.out.println("INSIDE ODB....>>>>>>>>>>>>>>" + lstBarring);
return this.lstBarring;
}
Problem is:
- 1st SOP is KEY-printing all the key correctly.
- 2nd SOP is VALUE-printing all the value correctly.
- 3rd SOP is VALUE IN KEY—-printing all the values.
- 4th SOP is VALUE IN VALUE–printing all the values.
Hence after ever iteration I am getting value,value in HashMap whereas it should be key,value.
Here’s look at my Method:-
public ArrayList<String> setPreParameters(HashMap<Integer,String> fetchPreDetails,int index)
{
switch(index)
{
case 1:
{
arrLstData.clear();
splittedString=fetchPreDetails.get(1).split(",");
Collections.addAll(arrLstData, splittedString);
break;
}
return arrLstData;
Please guide me as to where am I going wrong.
My guess is that either
fetchPreDetailsis a collection being mutated bysetPreParameters()or elsesetPreParameters()is mutating some other shared state so that the collection referenced by yourtemparrLstis being changed on the second call tosetPreParameters(). I.e.I expect your code assumes that
stringswould contain “a” and “b” and thatotherStringswould contain “a”, “b”, and “c”. This isn’t how object references work in Java. The lineList<String> otherStrings = strings;makes bothstringsandotherStringspoint to the same collection, and thus changes made using either name affect the same thing.Edit: Your newly-posted code seems to prove my hypothesis. You have a variable called
arrLstDatathat you clear, populate, and return on each call tosetPreParameters(). You’re returning the same collection every time you call this method. Therefore you just have multiple handles to the same collection instead of multiple collections. You need to create a new collection and return it each time you callsetPreParameters().Edit again: Maybe this will make it clearer. Here’s what you’re doing:
Note that this exhibits exactly the behavior that you’re describing, and the correct way to solve it is something like this: