I am having some trouble with NullPointExceptions when attempting to concatenate two linked lists in JAVA.
The code for main to test it is:
d1 = new MyDeque ();
d2 = new MyDeque ();
d2.pushLeft (11);
d1.concat (d2);
While the code for the concat function is:
public void concat (MyDeque that) {
if (!that.isEmpty())
{
this.last.next = that.first;
this.N += that.N;
that.first = null;
that.last = null;
that.N = 0;
}
}
The portion that I don't understand is that it flags NullPointerException. "d2" or that isn't empty, and "d1" is, which sort of makes me understand that there would be a null value, "d1", pointing to the first value in "d2", aka 11, with this.last.next = that.first. Should I make another statement that handles this differently if "d1" is empty as well?
Although I don't have your entire node class, I see 2 possible places for you to have a NullPointerException.
(1)
if (!that.isEmpty())
You should verify (that != null). Your code will throw a NullPointerException if that is null.
(2)
this.last.next = that.first;
Your code will throw a NullPointerException if this.last is null. Make sure it isn't, or check beforehand.
Make sure you are checking that the next node is not empty
while (list.next != null)
Is the standard approach, it may be slightly different if you are using a custom end token
Related
I have a homework to do in java about ArrayList and Generics types.
I have 2 classes :
-> CoupeDeA
-> TableauPartiel
CoupeDeA is just a describer from where to where an array is cut.
(It contains only two private integer variables "begin" and "end")
TableauPartiel is the class where the ArrayList is.
My problem is I need to create a method in TableauPartiel like this :
public TableauPartiel<E> coupe(CoupeDeA coupe)
And the TableauPartiel returned needs to be a reference of my intial TableauPartiel. Example :
Integer[] arr = {8,7,6,5};
TableauPartiel<E> tab = new TableauPartiel<>(arr);
TableauPartiel<E> tab2 = tab.coupe(1,3);
tab2.set(1,45);
This code is supposed to set 45 at index 1 of my tab2 and at the same time set 45 at index 2.
But I tried many different ways and I managed to get the sublist, but it is not pointing to my original ArrayList.
For example, I tried something like this :
private ArrayList<E> tableau;
...
public TableauPartiel<E> coupe(Coupe coupe)
throws IndexOutOfBoundsException {
if (coupe.getBegin() >= 0 && coupe.getEnd() <= tableau.size()) {
TableauPartiel<E> tab = new TableauPartiel<>((E[]) new Object[coupe.getEnd()-coupe.getBegin()]);
for (int i = 0; i < coupe.getEnd()-coupe.getBegin(); ++i) {
tab.set(i, this.get(coupe.getBegin()+i));
}
return tab;
} else {
throw new IndexOutOfBoundsException();
}
}
How can I do to get a sublist which refers to his original ArrayList?
I've found a solution for my code with the subList method and by switching the signature of my ArrayList to List but my teacher doesn't want us to use subList finally.
Here is my code with the subList method :
TableauPartiel<E> tab;
if (coupe.getDebut() >= 0 && coupe.getFin() <= taille()) {
if (coupe.getFin() == -1)
tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),taille()));
else
tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),coupe.getFin()));
return tab;
} else {
throw new IndexOutOfBoundsException();
}
}
Few small things first:
stick to English words in your code. Especially in names of classes, functions, variables, etc - names have to reveal intentions (without Google Translate). Best not to obtain a bad habit by letting yourself do otherwise.
I am not so sure how your Coupe is expected to work (is 0 a legal min number or 1?) but coupe.getEnd() <= tableau.size() might get out of hand
Now my suggestion for the solution:
I suggest you modify your TableauPartiel class to have start and end integer fields in addition to private ArrayList<E> tableau; reference you already have. Maybe add a new 'copy constructor' accepting an instance of
TableauPartiel (from which you can copy reference to tableau) and two int values indicating which part of the original tableau you can use (trick here is to also look at start and end values of the object you're 'sublisting' from). That way, when you're calling #coupe you can check for validity of the input numbers (as you already do) and simply return a new TableauPartiel object with a reference to this and method params - start and end values. Add some indexes manipulation logic using those start and end to whatever methods your TableauPartiel has and you should be good to go.
my question is really, really simple, but everything I find online tells me I am doing it the right way - but I obviously misunderstood something.
I have a simple, simple Java ListIterator, which in a while-hasNext()-loop returns a null for next(). Here's the code with my comments on the debug state:
[...]
ListIterator<Role> rolesIterator = currentUser.getRoles().listIterator();
// rolesIterator is now: java.util.ArrayList$ListItr
while( rolesIterator.hasNext() ) {
Role roleObject = rolesIterator.next(); // extra step for debugging reasons
String role = roleObject.getName(); // NullPointerException - roleObject is null
[...]
In my thoughts, the loop should not be entered, if there is no next() object - that's why I check using hasNext(). What did I understand wrong, and what is the correct way?
There is a next element in the list, and this next element happens to be null. For example:
List<String> list = new ArrayList<>();
list.add("foo");
list.add(null);
list.add("bar");
The above list has 3 elements. The second one is null.
Fix the code that populates the list and make sure it doesn't add any null Role in the list, or check for null inside the loop to avoid NullPointerExceptions.
ListIterator documentation states that next():
Throws:
NoSuchElementException - if the iteration has no next element
Furthermore, you do the appropriate hasNext() check as the loop condition. So the obvious conclusion is that currentUser.getRoles() contains null elements. To fix [this part of] your code:
while( rolesIterator.hasNext() ) {
Role roleObject = rolesIterator.next();
if(roleObject != null)
{
String role = roleObject.getName();
[...]
}
I believe list can contain null values.
so the roleObject can be null.
I prefer the for loop approach (cleaner):
for (Role roleObject : currentUser.getRoles()) {
...
}
For some reason I am receiving errors in the code below and I can't see why, can you spot any?
public void delTask_mouseClicked(MouseEvent e)
{
if(delTask.isEnabled() == false) {
int numTasks = taskTable.getRowCount();
Object[] currentTasks;
currentTasks = new Object[numTasks];
for (int i = 0; i < numTasks ; i++){
Object tasks = taskTable.getModel().getValueAt(i, 1);
currentTasks[i] = tasks;
}
System.out.println(currentTasks);
}
}
Thanks for the help, it's really appreciated.
There massive block of errors I am getting is below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at projecttaskmanagement.ProjectGUI.delTask_mouseClicked(ProjectGUI.java:233)
at projecttaskmanagement.ProjectGUI$2.mouseClicked(ProjectGUI.java:109)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:212)
at java.awt.Component.processMouseEvent(Component.java:5520)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3901)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
CODE AT LINE 233:
int numTasks = taskTable.getRowCount();
TASK TABLE IS DEFINED BELOW:
String[] taskcolumnNames = {"ID #",
"Name",
"Description",
"Start Date",
"End Date",
"Staff",
"Completed"};
Object[][] taskdata = {
{new Integer(1), "Requirements Analysis",
"Analysing the requirements",
"01/09/2011", "15/10/2011",
"Bob", new Boolean(true)},
{new Integer(2), "System Design",
"Designing the System",
"15/09/2011", "15/10/2011",
"Alice", new Boolean(true)},
{new Integer(3), "Code (A)",
"Part 'A' of coding",
"01/10/2011", "15/11/2011",
"David", new Boolean(true)},
};
JTable taskTable = new JTable(taskdata, taskcolumnNames);
While we're waiting for you to post the actual errors you're getting (a), please take a moment to NEVER do this:
if (delTask.isEnabled() == false)
A much better form is the simpler-to-read:
if (! delTask.isEnabled())
We now return you to your scheduled programming, pending your update.
Dum de dum de dum ...
Now, based on your update, the following part of the stackdump:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at projecttaskmanagement.ProjectGUI.delTask_mouseClicked(ProjectGUI.java:233)
indicates where the problem lies. Find out which of those lines of yours in line number 233 and there you have it. The thing that you're trying to deference on that line is in fact a null reference.
Based on the snippet, it'll probably be one of the following lines:
public void delTask_mouseClicked(MouseEvent e)
{
if(delTask.isEnabled() == false) { // <--
int numTasks = taskTable.getRowCount(); // <--
Object[] currentTasks;
currentTasks = new Object[numTasks];
for (int i = 0; i < numTasks ; i++){
Object tasks = taskTable.getModel().getValueAt(i, 1); // <--
currentTasks[i] = tasks;
}
System.out.println(currentTasks);
}
}
The first will be because delTask itself is null, the second if taskTable is null.
The third will be if taskTable itself is valid but the value returned from its getModel() method is null.
So, it appears that your taskTable is null. As to why this is so, that's unknowable based on the current information. What you will need to do is examine all the places it's set to a valid value and ensure that this happens before you (or more likely, AWT under the control of your user) call this method.
And of course, make sure it's not set back to NULL at some point after creation.
If you can't guarantee that, you'll probably need to change:
if (delTask.isEnabled() == false)
into something like:
if ((! delTask.isEnabled()) && (taskTable != NULL))
but my preference would be to fix the root cause of the problem rather than applying this band-aid.
Your code that creates the JTable seems okay (syntactically) but there's the slight mystery of where that's done. Is it created in a manner that it's usable from where you're trying to use it.
For example, if that code that creates it is within the constructor, that particular taskTable would be local to said constructor (and destroyed on exit), not usable from elsewhere. In that case, it needs to be made an object-level variable so that other methods can get to it.
You can see that effect in the following program:
public class testprog {
public Object thingOne;
public Object thingTwo;
public void someFunction() {
thingOne = new Object();
Object thingTwo = new Object();
}
public void debug() {
if (thingOne == null)
System.out.println ("thingOne is NULL");
else
System.out.println ("thingOne is valid");
if (thingTwo == null)
System.out.println ("thingTwo is NULL");
else
System.out.println ("thingTwo is valid");
}
public static void main(String args[]) {
testprog tp = new testprog();
tp.someFunction();
tp.debug();
}
}
This outputs:
thingOne is valid
thingTwo is NULL
because thje thingTwo set up in someFunction() is a local version and does not in any way set up the object-level thingTwo - the object level one remains as null and, if you try to dereference it, you'll see the same problem you're having.
(a) The best problems reports come with a small, complete code snippet exhibiting the problem, the expected behaviour, and the actual behaviour.
If we post that sample of yours into a naked Eclipse Java program, it's very much not complete. MouseEvent, delTask and taskTable have no definitions and, without that information, it's a little hard to debug.
In addition, Eclipse (for syntax errors) and Java itself (for runtime errors) are perfectly able to tell you in great detail what your problems are, and you should read what it's telling you. You should also communicate that information to us if you want help :-)
Which line is line 233 of ProjectGUI.java? At least one of the following is null:
delTask
taskTable
taskTable.getModel()
Figure out which of those falls on line 233 (per your error report), and you've figured out where the problem lies. We'll need to see more code to determine why the variable does not have the expected value.
Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.
I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null