Reputation: 267
I have working on a problem where I am given a map (called myMap
) where the keys are the names of authors, and the values are the names of the co-authors that the written has published articles with. I have to create a method that returns a String array containing the degrees of separation between a particular author, named ERDOS, and the other ones. I have written up the code below to do so; I am using a breadth first search.
HashMap<String,Boolean> visitedMap= new HashMap<String,Boolean>();
HashMap<String,Integer> distanceMap=new HashMap<String,Integer>();
for(String name: myMap.keySet()){
visitedMap.put(name, false);
}
for(String name:myMap.keySet()){
distanceMap.put(name, -1);
}
distanceMap.put("ERDOS", 0);
Queue<String> q= new LinkedList();
q.add("ERDOS");
visitedMap.put("ERDOS", true);
int i=0;
while(!q.isEmpty()){
String a = q.remove();
i=i+1;
ArrayList<String> current= myMap.get(a);
for(String z:current){
System.out.println(current);
System.out.println(visitedMap);
if(visitedMap.get(current)==true){
q.add(z);
distanceMap.put(z, i);
visitedMap.put(z,true);
}
else{
break;
}
}
}
ArrayList<String> answer= new ArrayList<String>();
for(String y:distanceMap.keySet()){
answer.add("y"+" "+Integer.toString(distanceMap.get(y)));
}
String[] realAnswer= answer.toArray(new String[answer.size()]);
Arrays.sort(realAnswer);
return realAnswer;
}
However, I keep getting a null-pointer error when I call (visitedMap.get(current)==true). The two print statements before this line show that current is definitely present in visitedMap, and so I really don't understand the cause of this null-pointer exception. I would really appreciate any help. Thanks a lot!
Upvotes: 0
Views: 139
Reputation: 206816
current
is an ArrayList<String>
, while the keys in your map visitedMap
are String
objects. Therefore, visitedMap.get(current)
will always return null
.
You probably wanted to use: visitedMap.get(z)
instead of visitedMap.get(current)
.
Upvotes: 2