Java linkedlist with objects - null pointer exception [duplicate] - java

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);
}
}

Related

What is the most efficient way to conditionally log information? [duplicate]

This question already has answers here:
Does log.debug decrease performance
(5 answers)
Closed 2 years ago.
I don't really know what is the best way to log information from an application. Most of what I've seen is programmed like this:
while(true) {
//code
if(debug == true) {
log(info);
}
end
And I've thought of using two separate loops like this:
if(debug == true) {
while(true) {
//code
log(info);
}
else {
while(true) {
//code
}
}
But that has the problem of being twice the work to change later on. The last solution, which I think is probably the best, is to use something like a lambda expression and pass an empty implementation to use without debug:
public void loop(Debug debug) {
while(true) {
//code
debug.log(info)
}
}
public static void main(String[] args) {
loop(d -> {
//print to file, command line, etc. OR do nothing
});
}
Any clarity on issues or unintended consequences would be greatly appreciated.
Thanks in advance!
Don't try to invent a bicycle. Use existing logging frameworks and follow their guidelines.
Whatever you will think of - you will need to get over same problems that are already solved there.
For example https://logging.apache.org/log4j/2.x
Or http://www.slf4j.org/

Java NullPointerException in .containsKey [duplicate]

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.

Why IF condition is not fulfilled on android [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I just want to know why the compiler allow to continue the program normally in the first condition:
public void ButtonOnClickDirectoryList(View v){
try {
if (!spnOptionSelectedDepartment.equals(null) && !spnOptionSelectedCities.equals(null)) {
if (!spnOptionSelectedTypes.equals(null)) { //code....}
the spnOptionSelectedDepartment and spnOptionSelectedTypes are Strings and are defined at the begining of the class like this:
private String spnOptionSelectedDepartment = null;
private String spnOptionSelectedCities = null;
private String spnOptionSelectedTypes = null;
so when I press the button, it call this method and this are the values that I have in the moment:
spnOptionSelectedDepartment = "9999"
spnOptionSelectedCities = null
spnOptionSelectedTypes = null
so when I put a break point on this condition it just continue validating the rest of the code inside that if...
Could anybody explain me why this behavior?
Let me edit the question, Yes it throws nullpointer exception on the second if...
if (!spnOptionSelectedTypes.equals(null)) {
but why it allows the first IF when spnOptionSelectedCities = null...?
It shouldn't continue, it should throw a NullPointerException that you may intercept in the catch block.
When you try
if (!spnOptionSelectedTypes.equals(null))
it should throw this exception because spnOptionSelectedTypes is null so it is not a String and does not have any equals() method.
Edit:
It allows the first if to pass because it has 2 tests
if (A OR B) {
If A is true, the B condition is not tested because only one is required to continue, because of the OR operator.
Edit 2:
With:
if (A AND B) {
If A is true, B will also be tested and throw a NullPointerException if spnOptionSelectedCities is null.
Definitive answer:
Null tests in Java
if (x != null && y != null) {
x.doSomething();
y.doSomethingElse();
}

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

Having issues with List in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have this class:
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
}
And when I do:
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
It gives Exception in thread "main" java.lang.NullPointerException
Weirdly tho, it only gives an error on "angle.isEmpty()" not on "text.isEmpty()"
Why does it say it is null when I initialize it with:
List angle = new ArrayList();
Edit1:
Full error:
Exception in thread "main" java.lang.NullPointerException
at projectmerger1.Attributes.getHowManyNodes(Attributes.java:55)
at projectmerger1.Project.listGameVariables(Project.java:235)
at projectmerger1.ProjectMerger1.main(ProjectMerger1.java:289)
Java Result: 1
Minor edit:
Line 55 in Attributes Class is
howMany += angle.isEmpty() ? 0 : angle.size();
Edit2:
public class Project {
Game game;
public void listGameVariables() {
System.out.print(game.attributes.getHowManyNodes());
}
}
public class Game {
Attributes attributes = new Attributes();
}
This is my whole setup.
Based on your comments (and your code) one (or both) of your List(s) must be null. I would add a null check like this
howMany += text == null ? 0 : text.size();
howMany += angle == null ? 0 : angle.size();
It's possible you have another method that is "nulling" those fields.
I've compiled and run this code, it prints out 0 with no NullPointerException. There is no way to get this error with the code you provided.
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
public static void main(String[] args) {
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
}
}
The only possible way that this could be happening is if:
angle is being accessed somewhere else and set to null before you call getHowManyNodes().
angle is being "shadowed" by another variable of the same name that you are not showing in your code example.
Ways to debug this:
Make your variables private and final, and see what code they break so you can see if they're being set to null elsewhere.
Put System.out.println(angle) in a block of code under your instantiation of angle, and also in your constructor.
Ways to avoid this bug in the future:
Encapsulate your variables.
Make your methods null-safe.
Set a BreakPoint in the first source code line of your getHowManyNodes() method, start your program in debug mode and try to figure out where the error comes from by using the short cut keys (Eclipse) F5 -> StepInto and F6 -> StepOver. Your source provided looks fine and shouldn't cause any problems. By debugging your application via Eclipse or any other IDE, you should easily find such errors.

Categories

Resources