Collection holds value as a refernce in java

Value as a Reference example : Here we are fecthing a list from a collection and updating this which leads to automatic update of Map because numList is directly referring to  testmap.
-----------------------------------


public class ValueAsReference{

enum EvenOdd{
EVEN,ODD
}
public static void main(String ... arg){

Map<String,List<String>> testmap=new HashMap<String, List<String>>();
for(int i=0;i<20;i++){
String key="";
if(i%2 ==0){
key=""+EvenOdd.EVEN;

}else{
key=""+EvenOdd.ODD;
}
List<String> numList=testmap.get(key);

if(numList==null){
numList=new ArrayList<String>();
numList.add("i="+i);
testmap.put(key, numList);
}else{
numList.add("i="+i);
}
}
for(String key : testmap.keySet()){
System.out.println("key : "+key);
System.out.println(testmap.get(key));
}

}
}
--------------------------------------
Output :
key : EVEN
[i=0, i=2, i=4, i=6, i=8, i=10, i=12, i=14, i=16, i=18]
key : ODD
[i=1, i=3, i=5, i=7, i=9, i=11, i=13, i=15, i=17, i=19]


Popular posts from this blog

Can not connect to git using ssh (Permissions 0644 for '/root/.ssh/id_rsa' are too open.

Upload file on Google cloud storage using Java servlet on google app engine

Android: where to run keytool command in android