Java NullPointerException in .containsKey [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm very new to Java. Trying to access a field in the HashMap observationMap, and am told there is a NullPointerException when I check if the HashMap contains the key. In particular, in the getEventSpeed() method.
.containsKey() should return NULL, so not clear how this line causes issue for the if statement?
Thank you for your help
public class IsDrivingObservation {
private Map<String,String> observationMap;
public String getEventSpeed() {
if (observationMap.containsKey("eventSpeed")) {
return observationMap.get("eventSpeed");
}
return "foo";
}
public void setEventSpeed(String speed) {
observationMap.put("eventSpeed", speed);
}
}

you never create the observationMap. Try this:
private Map<String,String> observationMap = new HashMap<>();
otherwise you will get the NPE in both of your methods.
That depends on which method you call first.

Related

Why is the link list merge function not working in Java? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
The problem arises in the merge function at 'while(m.next!=null)'. It throws a "NullPointerException".
public class Linked {
node ptr1;
node ptr2;
void merge()
{
node m=ptr1;
while(m.next!=null)
m=m.next;
m.next=ptr2;
}
void printmerged()
{
node m=ptr1;
while(m.next!=null)
System.out.print(m.data+", ");
System.out.println(m);
}
}
I added comments to your code to explain to you what's going on.
node ptr1; //ptr1 is null here
node ptr2;
void merge()
{
node m=ptr1; //you are assigning null to m
while(m.next!=null) //you are accessing the "next" property of a null object
m=m.next;
m.next=ptr2;
}
You have to instantiate your objects otherwise they are going to be null.

How to replace if(Optional.isPresent()) with an expression in functional style [duplicate]

This question already has answers here:
How to execute logic on Optional if not present?
(14 answers)
Closed 4 years ago.
I have the following block of code:
Optional<Integer> result = //some method that returns an Optional<Integer>;
if(result.isPresent()) {
return result.get();
} else {
return 0;
}
and my IntelliJ suggests that I replace it with a functional expression. I see that there is a method ifPresentOrElse() inside Optional but I can't possibly figure out how to use it in this particular case.
Any suggestions? Thanks!
Looks like orElse() is what you'd want here. https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElse-T-
Optional<Integer> result = //some method that returns an Optional<Integer>;
return result.orElse(0);

Java linkedlist with objects - null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Full code here: https://pastebin.com/ntSZ3wZZ
Okay so something must be going horribly wrong with my constructors in a linkedlist program I am trying to create.
Here is what my program is supposed to do:
// running
add 3.0 3.0 Three
add 2.0 2.0 Two
add 1.0 1.0 One
print
One{0} +1.0, +1.0
Two{0} +2.0, +2.0
Three{0} +3.0, +3.0
Here is what happens:
add 3.0 3.0 Three
Exception in thread "main" java.lang.NullPointerException
at Pet.setLat(Pet.java:37)
at Pet.newPet(Pet.java:24)
at Pet.<init>(Pet.java:18)
at PetList.insertFront(PetList.java:23)
at Exe.main(Exe.java:14)
I feel like I am using a null reference (if that's how you call it). But I can't figure out where or how! I know it's a vague question but I don't know how else to ask it. If there is some edits I can make to my question to make it more easy please let me know. Thank you for any help!
Here is some of my code:
public Pet() {
name = "";
treats = 0;
coor = new Coordinate();
}
public Pet(Pet copy) {
if(copy == null) {
name = "";
treats = 0;
coor = new Coordinate();
return;
}
newPet(copy);
}
public void newPet(Pet copyTwo) {
setName(copyTwo.name);
setTreats(copyTwo.treats);
setLat(copyTwo.getLat()); // error here line 24
setLong(copyTwo.getLong());
}
public void setLat(float newLat) {
coor.setLatitude(newLat);
}
your problem is that your copy-constructor doesn't initialize coor before you call setLat(). Change your public Pet(Pet copy) to:
public Pet(Pet copy) {
this();
if(copy != null) {
newPet(copy);
}
}

Why synchronized object give null pointer Exception if we are adding null key as a Object.? [duplicate]

This question already has answers here:
Why does ConcurrentHashMap prevent null keys and values?
(7 answers)
Closed 6 years ago.
Here i have sample of code for Hash Table and Concurrent Hash Map which does not allow null key as a Object But Both are Synchronized.
public class Example
{
public static void main(String[] args)
{
ConcurrentHashMap<String,String> premiumPhone =
new ConcurrentHashMap<String,String>();
premiumPhone.put("Apple", "iPhone");
premiumPhone.put("HTC", "HTC one");
premiumPhone.put(null,"S5");
Iterator iterator = premiumPhone.keySet().iterator();
while (iterator.hasNext())
{
System.out.println(premiumPhone.get(iterator.next()));
premiumPhone.put("Sony", "Xperia Z");
}
}
}
From the Javadoc for ConcurrentHashMap
Like Hashtable but unlike HashMap, this class does not allow null to
be used as a key or value.
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html
Also, take a look at this: https://stackoverflow.com/a/9298113/2227788

Java - weird ConcurrentModificationException [duplicate]

This question already has answers here:
Java Set gets full
(2 answers)
Closed 8 years ago.
I loop through a copy of a set of objects, but it still gives me an error starting at this method:
private static Set<Updated> updates = new HashSet<>();
public static Set<GameObject> getGameObjects() {
Set<GameObject> objs = new HashSet<>();
for (Updated up : new HashSet<Updated>(updates)) {
if (up instanceof GameObject)
objs.add((GameObject) up);
}
return objs;
}
(Where the for loop is).
This only happens when there are quite a few GameObjects, and never occurs when there's only a few (like 7). Thank you!
The problem is that somebody in another thread changes the updates set while it is being copied in new HashSet<Updated>(updates).
You cannot do this without synchronization. Or use ConcurrentHashMap instead of HashSet

Categories

Resources