NullPointerException when adding to List - java

I am trying to iterate through a list of objects to figure out which ones are fighting each other. I am using the checkedGladiators list as something to compare against to prevent it from checking gladiators already assigned to a combat, as each s that isn't assigned already will build their entire combat around them. Currently I get a NullPointerException, so I used some test text to figure that it was happening right at listContains(checkedGladiators,s). I added the part before it. NOW the problem is happening between "Null" and "Null Changed" as well, which makes no sense to me.
for (Gladiator s : gladiators) {
if (checkedGladiators == null) {
System.out.println("Null");
combat1.add(s);
checkedGladiators.add(s);
System.out.println("Null Changed");
}
if (listContains(checkedGladiators, s)) {
// if gladiator is already in a combat do nothing
} else { // if he isn't
}
}
listContains class:
public boolean listContains(List<Gladiator> List, Gladiator search) {
for (Gladiator p : List) {
if (p.equals(search)) {
return true;
}
}
return false;
}
Does anyone know why this would occur? Thanks
Edit1:
public class Ai {
private List<Gladiator> gladiators;
private List<List<Gladiator>> combatsList;
private List<Gladiator> checkedGladiators;
private List<Gladiator> combat1;
private List<Gladiator> combat2;
private List<Gladiator> combat3;
private List<Gladiator> combat4;
private List<Gladiator> combat5;
private List<Gladiator> combat6;
private List<Gladiator> combat7;
private List<Gladiator> combat8;
private List<Gladiator> guardList;
private List<Gladiator> advanceList;
private List<Gladiator> retreatList;
int totalCombats = 0; // total combats going on
I have initialized the list variable in the class already.

You are forgetting to create the checkedGladiators object.
So, create the object before your loop as:
List<Gladiators> checkGladiators = new ArrayList<Gladiators>();
Then, in your loop, rather than testing for checkGladiators == null...
test for checkGladiators.isEmpty().

if(checkedGladiators ==null) is true and you are adding something to it ,
it will definitely throw a NullPointerException , because you are operating on null
Thanks
Abhi

Why do you need to do all this? Why isn't this sufficient?
// This has your data in it.
List<Gladiators> gladiators = new ArrayList<Gladiators>();
// Obviously some attributes, including a unique key or name.
// MUST override equals and hashcode properly
Gladiator g = new Gladiator();
if (gladiators.contains(g)) {
// do something here.
}
NullPointerException is one of the easiest problems to fix. Run your code in an IDE with debugging turned on and put a breakpoint where the stack trace says the exception occurred. You'll figure out quickly why something you assumed should not be null has violated your assumptions.

Instead of checking with System.out.println, use StackTrace or a debugger like eclipse. I will pin-point clearly.
if (checkedGladiators == null) {
System.out.println("Null");
combat1.add(s);
checkedGladiators.add(s); --> checkedGladiators is null here. Here null pointer exception will occur.
System.out.println("Null Changed");
}

you check if checkedGladiators is null and then call a method on it:
if (checkedGladiators == null) { // <-- null!!
checkedGladiators.add(s); // <-- null pointer exception.
}

When checkedGladiators is null you try to add to it (as if it were a List/Collection/etc).
...
if (checkedGladiators == null) {
...
checkedGladiators.add(s); // <-- You handle 'checkedGladiators'
// <-- as an instaciated, when it is 'null'
Do this instead:
...
if (checkedGladiators == null) {
...
checkedGladiators = new ArrayList<...>(); // <-- instanciate appropriately
checkedGladiators.add(s);
...

Related

Why without 'else', it will throw java.lang.NullPointerException in preoder traversal of a BTree?

I am new to programming. My question might be dumb. (***If there is no value for others, I will delete this question later)
See these two functions here:
1.
StringBuilder sb = new StringBuilder();
private String preorder(TreeNode root) {
if(root == null){
sb.append("null,");
}
sb.append(root.val);
sb.append(",");
String l = preorder(root.left);
String r = preorder(root.right);
return sb.toString();
}
2.
StringBuilder sb = new StringBuilder();
private String preorder(TreeNode root) {
if(root == null){
sb.append("null,");
}
else{
sb.append(root.val);
sb.append(",");
String l = preorder(root.left);
String r = preorder(root.right);
}
return sb.toString();
}
If I call these two functions in the main function.
The 1st one will threw
java.lang.NullPointerException error.
I understand that when java.lang.NullPointerException occurs:
1. when declare a variable but did not create an object
2. assign to the variable before trying to use the contents of the variable
(update on this part:
After IF condition, regardless there is a else or no, it will execute the rest of body, thanks for everyone's help)
(Stale. Ignore the rest of part: )
After
if(root == null)
the rest should be
root != null
Correct me if I am wrong.
Answer
You are missing an else case.
private String preorder(TreeNode root) {
if(root == null){
sb.append("null,");
}else{
// ...
}
The code below your if condition will still execute if you do not add an else
or return.
It will throw an NPE because after your condition you
try to access root with:
sb.append(root.val);
Further Explanation
You need to read it like a sentence.
if(thisIsTrue){
// Then do that
}else{
// Do that
}
Where "thisIsTrue" is your condition. i.e root != null.
If you try to access a member of root with root.val,
where you try to acces val, then root must not be null,
or an NullPointerException will be thrown.
Metaphorically speaking..imagine you have a bag of apples.
What you are trying to do, is to grap an apple, but you have no bag.
I think this is clear.
If you omit the else clause, then it will execute like the following:
if(thisIsTrue){
// It will do that, if condition is true
}
// It will ALWAYS execute this, even if condition is false
With if/else
You open two branches. Only one of them gets executed.
With if, but no else
You have one conditional branch that gets execute if the
condition is true, but the code underneath will be execute always afterwards.

null pointer exception from my code from the while loop

I decleared free block like
private DoublyLinkedList freeblock = new DoublyLinkedList();
and I initialize the freeblock in the constructor.
freeblock.add(new DoublyLinkedList.Node(null, null, 0, initBlockSize));
inside of one of method of my class, (below is part of my method.)
I get null pointer exception. I think the while loop has a problem. Can anyone help me to solve this problem?
symptom: java.lang.NullPointerException
at LinearMemPool.enlarge(LinearMemPool.java:220)
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node.next != null) {
node = node.next;
}
}
Evidently freeblock.head is null. Look what add does.
Your enlarge method seems a bit dangerous. Try changing the null check to:
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node != null) {
node = node.next;
}
}
As for the reason why your head is null, I'd debug the freeblock.add(...) method.
First check to see freeblock.head is null because most likely it is:
if(node!=null){
while(node.next!=null){
....
}
else{
System.out.println("Freeblock is null but why.....");
}
You probably should do this normally if the freeblock.head can ever be null. And just for cleaning up purposes:
void newMethod(Node node, int size){
if(node!=null)
enlarge(size);
else{
System.out.println("Freeblock is null");
}
}

Java List Listener throws Null pointer error, despite being able to access array

This is an listener for a list component. I get a null pointer error from when people select it, but I am still able to get the information I need from the array. The problem is the compiler still throws a null pointer event every time I click on the list item. How I am able to correctly access the array, while it still throws this error?
class facebookListListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
moodSetter.setEnabled(true);
String name = thePeople[facebookList.getSelectedIndex()].getName();
String mood = thePeople[facebookList.getSelectedIndex()].getMood();
Color lightGrey = new Color(160,160,160);
if(mood == null){
thePersonsMood.setText("default_mood");
thePersonsMood.setBackground(lightGrey);
}
if(mood.equalsIgnoreCase("happy")){
thePersonsMood.setText(name+"'s mood is " + mood);
thePersonsMood.setBackground(Color.RED);
}else{
thePersonsMood.setText(name+"'s mood is " + mood);
thePersonsMood.setBackground(lightGrey);
}
}
}
Ah, change this:
}
if(mood.equalsIgnoreCase("happy")){
to this:
} else // **** note the else!!!
if(mood.equalsIgnoreCase("happy")){
Otherwise you'll go into the if block even if the if (mood == null) test is true.

Nullpointer exception for Long variable [duplicate]

This question already has answers here:
Hibernate Parameter value [568903] did not match expected type [java.lang.Long]
(3 answers)
Closed 9 years ago.
I have the following code
private Long projectNumber; // with getters and setters
and when I am checking whether projectNumber is null or not, I am getting null pointer exception at the if condition
if(selected.getProjectNumber()!=null){
// do something
}
What could be the reason for this even though Long is a wrapper class.
If I change projectNumber from Long to String, it works fine.
Update 1
private Project selected = new Project();
public Project getSelected() {
return selected;
}
public void setSelected(Project selected) {
this.selected = selected;
}
I am getting selected value in ManagedBean of JSF in the following method
public void onRowSelect(SelectEvent event) {
}
projectNo getters and setters
public Long getProjectNo() {
return projectNo;
}
public void setProjectNo(Long projectNo) {
this.projectNo = projectNo;
}
The problem you have is because selected is null, projectNumber. Change the check to something like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
}
Or alternatively add a separate check for selected above.
If you get an NPE here:
if(selected.getProjectNumber()!=null){
and all getProjectNumber() does is return projectNumber, this strongly indicates that selected is null.
the problem is that selected is null. Check it like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
} else {
// here: selected = null OR projectNumber of selected is null
}
did you check if selected is null
you can do the following
if(null != selected)
{
if(null != selected.getProjectNumber())
{
// do something
}
}
Your object selected is apparently null, try to do:
if ((selected != null) && (selected.getProjectNumber()!=null)){
// do something
}
From what you posted, it sems that the problem is that the object referred by the selected variable is null. You have to check that too:
if(selected !=null && selected.getProjectNumber()!=null){
// do something
}
Explanation: Doing it this way, as the boolean AND (and the OR) operator evaluates only the left condition if it is false, not touching the right side, you won't get a NullPointerExceptyion anymore.
EDIT As OP mentioned that by changing the variable to String the problem is not encountered, as 0xCAFEBABE's suggestion implies, the same error might be possible if the getter returns (or somehow internally uses) a simple long value instead of a Long object, and the value of the variable is null:
/** error getter */
public long getProjectNumber() {
//this would trz to convert null, but what will it convert to? A NullPointerExecption...
return projectNumber;
}

Eclipse marks lines as dead code

I have this function with some dead code, marked by Eclipse.
I have two lines that check a & b. Lines that check b are marked as null.
public int[] runThis(List<Integer> buildIds, List<Integer> scenarios, boolean oflag) {
int rating[] = new int[scenarios.size()];
if(buildIds == null) {
System.out.println("ERROR - Building ID list is null!");
return null;
}
if(scenarios == null) {
System.out.println("ERROR - Scenario list is null!"); //dead
return null; //dead
}
return rating;
}
Why does Ellipse make the two lines as dead? Any help? Thanks very much for your time.
Because you've already called scenarios.size() in your array constructor. This guarantees scenarios isn't null or it will have thrown an exception by that point.

Categories

Resources