Null Pointer Exception Fix - Lists - java

public void createGraph () {
int oldFrom = -1;
int oldTo = -1;
for(int i = 0; i < edges.size(); i++) {
EdgeI e = edges.get(i);
int from = e.from;
int to = e.to;
VertexI v = vertices.get(from);
if (from == oldFrom && to == oldTo){
vertexWeight wic = v.neighbors.get(v.neighbors.size() - 1);
wic.w++;
}
else {
v.neighbors.add(new vertexWeight (to, 1));
oldFrom = from;
oldTo = to;
}
}
}
neighbors is a public List from VertexI class. w is a public integer from vertexWeight class. edges is a list located in my main class. I keep getting a null pointer exception for this line of code:
v.neighbors.add(new vertexWeight (to, 1));
Tried working on it for around 15 minutes and I didn't get it to work. What am I messing up on?
java.lang.NullPointerException
at tester.createGraph(tester.java:60)
at tester.main(tester.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

Short answer
Initialize v.neighbors with new ArrayList() in vertices.get().
Long answer
Your question omitted a crucial information: How you initialized neighbors. Why is this important?
See: What is a NullPointerException, and how do I fix it?
In your case I guessed that either v or neighbors is null during the run of the program. For example vertices.get(from) could return null and v.neighbors won't work. Or neighbors is null, and v.neighbors.add() won't work.
And voilĂ . You admitted that you set neighbors to null when initializing VertexI.
The solution is: Initialize with new ArrayList() instead of null.
If that would not have been possible or you cannot avoid null pointers for some other reason, you can do null pointer checks like this:
if (v != null && v.neighbors != null) {
v.neighbors.add(new vertexWeight (to, 1));
}
This means, don't add vertices if v or neighbors are null.
But this is complicated and error-prone. It is easier to avoid null pointers as much as possible. Some would say, avoid them at all costs! Throw an exception instead or return an "empty" object like new ArrayList().

Related

How to make a hash table throw an exception when inserting a null key (Java)?

For an assessment I need to create a hash table, which I have done. However, I need to throw an exception when inserting a null key.
The test I ran, which I need to pass, was:
#Test(expected = IllegalArgumentException.class)
public void testNullKey() {
Hashtable<Boolean> h = new Hashtable<>(10);
h.put(null, true);
}
Which gives me the error:
java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.lang.NullPointerException>
Caused by: java.lang.NullPointerException: Cannot invoke "String.hashCode()" because "key" is null
at Hashtable.hash(Hashtable.java:270)
at Hashtable.put(Hashtable.java:84)
at test.TestHT.testNullKey(TestHT.java:52)
Hashtable.hash(Hashtable.java:270) is:
private int hash(String key)
{
int hashVal = key.hashCode();
hashVal %= max;
if (hashVal < 0)
hashVal += max;
return hashVal;
}
and Hashtable.put(Hashtable.java:84) is:
public void put(String key, V value)
{
int h = 0;
if (getLoadFactor() > maxLoad)
resize();
h = probeType == PROBE_TYPE.LINEAR_PROBE ? hash(key) : doubleHash(key);
if (get(key) != null)
{
arr[h] = new Pair(key, value);
} else
{
arr[findEmpty(h, 0, key)] = new Pair(key, value);
itemCount++;
}
}
I am at a total loss for throwing an exception when inserting a null key. I've tried adding throw new IllegalArgumentException();and other attemps like that within put, but I can't get it to work.
Does anyone have any ideas or pointers?
OK. So this Hashtable class is your code, and not java.util.Hashtable. (You had me tricked for a minute there ...)
The solution is simple. Explicitly test the key to see if it is null and throw the required exception:
if (key == null) {
throw new IllegalArgumentException("key is null");
}
I'll leave you to figure out where the best place to put this code is.
The other approach would be to make NullPointerException the expected exception ... but my reading of your question is that that testcase is checking that a requirement is satisfied.

NullPointerException with a ticking entity Minecraft modding 1.8

Hello fellow coders,
I am writing a mod for Minecraft in 1.8 and have come across a pesky NullPointerException with my throwable. In the code below, the EntityThrowable uses an outer class to get the results of what will happen when thrown and the BlockPos passed is from the getBlockPos() method. This position is passed to the outer class where it transformed into x, y and z coords. However, whenever I throw the throwable, it throws an exception for these coordinates.
The difference between this question and the question of what is a NullPointerException is that the return value of what I am getting from the mov.getBlockPos() (from a MovingObjectPosition) is unknown. The MovingObjectPosition assigns the coords of the BlockPos from a random class and the coder of the Throwable gets the results. I am using the results for the outer class. These results in the ints cause the game to crash from unknown coords. If you have any idea of how to get the end pos of the throwable, that would be appreciated.
Here's the code:
Throwable:
#Override
protected void onImpact(MovingObjectPosition mov) {
LuckyPotionItems lpi = new LuckyPotionItems();
EntityPlayer player = this.getThrower() instanceof EntityPlayer ? (EntityPlayer) this.getThrower() : null;
if(!worldObj.isRemote)
lpi.chooseUnluckyDrink(worldObj, player, mov.getBlockPos());
this.setDead();
}
Outer Class:
public void chooseUnluckyDrink(World w, EntityPlayer p, BlockPos pos){
Random r = w.rand;
int number = r.nextInt(13);
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
System.out.println("Unlucky Number = " + number);
Thanks for any help.
It sounds like the problem could be solved by checking if the BlockPos and the EntityPlayer are not null. If they aren't null, then run the method. If they are null, simply prevent the method from being ran.
#Override
protected void onImpact(MovingObjectPosition mov) {
LuckyPotionItems lpi = new LuckyPotionItems();
EntityPlayer player = this.getThrower() instanceof EntityPlayer ? (EntityPlayer) this.getThrower() : null;
if(mov.getBlockPos() != null && player != null) {
if(!worldObj.isRemote)
lpi.chooseUnluckyDrink(worldObj, player, mov.getBlockPos());
this.setDead();
}
}
number = (number == null) ? "" : number;
System.out.println("Unlucky Number = " + number);
int x = (pos.getX() == null ) ? 0 : pos.getX();
you are getting a null value for the number which means there is no output in r.nextInt(13); you need to fix that. Im using a conditional statement to check the value of number if its null then it will assign a value for number which can then be printed. try with my example this would help you.

NullPointerException with ArrayList - should not be possible?

Today I got a NullPointerException at a point where it actually can't occur.
Exception in thread "Timer-9" java.lang.NullPointerException
at packagename.censored.Bot.changeServergroups(Bot.java:1363)
at packagename.censored.Bot.xpTask(Bot.java:1239)
at packagename.censored.Bot.access$7(Bot.java:1187)
at packagename.censored.Bot$9.run(Bot.java:729)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
This is the relevant part of the code:
public void changeServergroups(int cldbid, ArrayList<Integer> addList, ArrayList<Integer> removeList) {
// If there are groups to add AND delete, remove them from the lists
if (addList != null && removeList != null) {
ArrayList<Integer> temp = new ArrayList<Integer>(addList);
for (int s : temp) { // THIS IS LINE 1363
if (removeList.contains(s)) {
addList.remove((Integer) s);
removeList.remove((Integer) s);
}
}
}
// some more code, to do the actual group changes
}
How is it possible to get the NullPointerException there? I check to make sure that addList is not null before creating a new temporary ArrayList from it. Can someone tell me how this could possibly return in a NullPointerException?
The only possibility is that your list temp contains null. The null Integer is then unboxed to an int and that throws a NPE.
You can solve the NPE by using for (Integer s : temp) if having a null value is acceptable.

ObservableList throwing NullPointerException

I am adding some elements to an ObservableList in JavaFX and after adding some items I start getting NullPointerException for all the items I add. According to the JavaDoc the add() method throws NullPointerException when:
NullPointerException - if the specified element is null and this list
does not permit null elements
But as you can see while I'm debugging my element is NOT null:
So why I am getting this NullPointerException?
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at javafx.scene.chart.XYChart$Series$1.onChanged(XYChart.java:1525)
at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:158)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:72)
at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:155)
at java.util.AbstractList.add(AbstractList.java:108)
at sample.Main$1.handle(Main.java:115)
at javafx.animation.AnimationTimer$AnimationTimerReceiver$1.run(AnimationTimer.java:58)
at javafx.animation.AnimationTimer$AnimationTimerReceiver$1.run(AnimationTimer.java:56)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.handle(AnimationTimer.java:56)
at com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:359)
at com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:269)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:475)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:460)
at com.sun.javafx.tk.quantum.QuantumToolkit$13.run(QuantumToolkit.java:327)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
at java.lang.Thread.run(Thread.java:745)
Where sample.Main$1.handle(Main.java:115) is where I use the add() method.
EDIT:
It seems it only happens when I add the items inside things like TimerTask() or AnimationTimer():
new AnimationTimer(){
#Override
public void handle(long now) {
for (XYChart.Data<Double, Double> data : fullDataQueue){
chartData.add(data);
}
}
}.start();
Otherwise I'm not getting this expection!
EDIT 2:
Ok I think I know what the problem is, here is the test code:
#Test
public void testSeriesAddInAnimator(){
// Data
XYChart.Series<Double, Double> series = new XYChart.Series<>();
ConcurrentLinkedQueue<XYChart.Data<Double, Double>> fullDataQueue = new ConcurrentLinkedQueue<>();
ObservableList<XYChart.Data<Double, Double>> chartData = FXCollections.observableArrayList();
series.setData(chartData);
// Start adding data
final Random random = new Random();
for(int n = 0; n < 10000; ++n){
fullDataQueue.add(new XYChart.Data<>((double)n, random.nextDouble()));
}
new AnimationTimer(){
#Override
public void handle(long now) {
for (XYChart.Data<Double, Double> data : fullDataQueue){
chartData.add(data);
}
System.out.println("Stop!");
//stop(); -> Uncomment this and we get no exception!
}
}.start();
System.out.println("Done testSeriesAddInAnimator()!");
}
This seems to happens if I re-add existing data in the Series. It's not RT-37798 bug, but I think it's a bug too. If we comment stop() method inside AnimationTimer the same data will be re-added and we start getting all this NullPointerException.
The exception is in XYChart.java line 1525:
for(int i=c.getFrom(); i<c.getTo(); i++) {
getData().get(i).setSeries(Series.this);
// update linkedList Pointers for data in this series
if (begin == null) {
begin = getData().get(i);
begin.next = null;
} else {
if (i == 0) {
getData().get(0).next = begin;
begin = getData().get(0);
} else {
Data<X,Y> ptr = begin;
for (int j = 0; j < i -1 ; j++) {
ptr = ptr.next; // NPE HERE!!!!!
}
getData().get(i).next = ptr.next;
ptr.next = getData().get(i);
}
}
}
But if I try to remove all items in the ObservableList and then add the ones I want I get the NullPointerException related to the bug you mentioned (RT-37798). So it seems I'm doomed, nothing I can do until they fix the bug.
It looks like it isn't data, but one of datas components that is null.
I couldn't find matching source code, but if you look at
javafx.scene.chart.XYChart$Series$1.onChanged(XYChart.java:1525)
Im confident that you find a dereferencing of a component of data.
Ok it seems that RT-37798 bug is solved in JDK 8u20 Build 21. Will submit the bug I am having to see If I can get some response (https://javafx-jira.kenai.com/browse/RT-37824).
Thank you for your help!

about null pointer exception

Hi
I have written such this code but it will return this exception .and I do not know why please help me thanks.
private void Scan(DoublyLinkedList dList) { // T(n) = O(n)
DNode p1 = dList.getFirst();
while (p1!=null) {
DNode p2 = p1.next;
System.out.println(p1.getElement().toString()+"lol");
if (p2.next!=null) {
DNode p3 = p2.next;
if(p3.getElement()!=null){
boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());
if (b == true) {
p1 = p1.next;
} else {
p1.next = p3;
p3.prev = p1;
dList.remove(p2);
p1 = p1.prev;
}
}
else break;
}else break;}
}
public static double determinate(Object get, Object get0, Object get1) {
double data[][] = new double[3][2];
data[0][0] = ((Point) get).getX();
data[0][1] = ((Point) get).getY();
data[1][0] = ((Point) get0).getX();
data[1][1] = ((Point) get0).getY();
**data[2][0] = ((Point) get1).getX();**
data[2][1] = ((Point) get1).getY();
return ((data[0][0] * (data[1][1] - data[2][1])) - (data[1][0] * (data[0][1] - data[2][1])) + (data[2][0] * (data[0][1] - data[1][1])));
}
exception:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ConvexHull.Determinate.determinate(Determinate.java:55)
at ConvexHull.Determinate.isPointRightSide(Determinate.java:15)
at ConvexHull.GrahamVersion.Scan(GrahamVersion.java:104)
at ConvexHull.GrahamVersion.grahamScan(GrahamVersion.java:83)
at ConvexHull.GrahamVersion.<init>(GrahamVersion.java:25)
at UI.MainFrame.grahamButtonActionPerformed(MainFrame.java:221)
this will show that "p3" is null! but I have check "p3" why it returns "null" again?
I use strong for showing those lines that throws exception.
EDIT: Ihave edited my post but it will throw this exception for "p1"
One thing that looks wrong is:
if (!p3.equals(null))
This will generally always be true (if p3 != null) or throw a NullPointerException (if p3 == null)
The correct way to test whether p3 is not null is:
if (p3 != null)
Although that may not be why you're getting your NullPointerException
If the NullPointerException occurs on the line you highlight, it must be because get1 is null. This is passed in as p3.getElement(), so find out whether that could be null.
In theory, if data[2] was null then data[2][0] would throw a NullPointerException but since you initialize data then that won't be the problem in this case.
Also, is there some reason that your parameters for determinate() are Object instead of Point? If this is your actual code and not some simplified test-case, then the parameters should all be Point since that's what they must be.
Edit:
I see you've changed your original code to add some of the suggestions on this page.
But I still see some problems:
while (p1!=null) {
DNode p2 = p1.next;
if (p2.next!=null) {
// ^^^^^^^ If p2 is null, then this will throw NullPointerException
DNode p3 = p2.next;
if(p3.getElement()!=null){
// ^^^^^^^^^^^^^^^ If p3 is null, then this will throw NullPointerException
boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());
// ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ if one of these returns null then isPointRightSide() will throw a NullPointerException
I'm pretty sure you got the wrong line, because this:
!p3.equals(null)
will not work - that line (or those involving p1 or p2) is throwing the Exception. You cannot invoke any method on a null, including equals(). Use this instead for all your null checks:
p3 != null

Categories

Resources