"If" makes NullPointerException - java

I'm writing program, which do some operations with doublylinked lists(my implementation).
There is one thing which i do not understand and it confusing me a lot.
Ok. So. I have two doubly linked list. I need to create method where argument is a index of first doublylinked list, and on that index i need to put second list.
I wrote that method:
public void PutInPlace(int i){
DoublyLinkedList ldw3 = new DoublyLinkedList(); // New doublylinked list.
Node current = ldw1.tail; // ldw1 - First doublylinked list, created earlier.
Node current1 = ldw2.tail; //ldw2 - Second doublylinked list, created earlier.
int counter = 0;
while(true){
ldw3.AddHead(current.number);
current = current.prev;
counter++;
if(counter == i){ // THAT if makes NullPointerException
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
if(current1 == null)
break;
}
}
I dont wanna put all code, because it is long and can be not-easy to read. So, why "if(counter == i)" makes NullPointerException? Without that "if" program works. Where is the problem?
Thank you for help, guys!

current1 may be null. But you are trying to get the value
if(current1 != null)
{
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
}
instead of
current1 = current1.prev;
(or)
change the statement like this,
if(current1 == null)
break;
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
instead of
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
if(current1 == null)
break;

I think the current variable is the one being null. The i variable has a unique value, let's say 3.
While(true) is an infinite loop, and your condition (counter==i) will be executed only once (since you always increment counter and it will hit the value 3 only once). So unless current1 has no previous, the break will never be it and you will arrive to a point where current has no more previous (making it null and giving an exception when doing current.prev)
A good practice is always checking if an object is null before using one of its methods or attributes.

No, that "if" cannot make a NullPointerException.
First, make sure you recompile everything, and run a test. Then post the output from that test, including the stack trace from the exception.
Second, post the source code verbatim (so the line numbers are clear).
Third, post the javap output for the PutInPlace method.

Related

Recursion reverse a SingleLinkedList and print as a String

I was given the task to add a method reversed to a SingleLinkedList using recursion preferably.
public String reversed() {
StringBuilder b = new StringBuilder();
reversed(first, b);
return b.toString();
}
private void reversed(Node<E> n, StringBuilder b) {
if (n != null) {
reversed(n.next, b);
b.append(n.element);
b.append(’\n’);
}
}
Seems to work very well when I test in eclipse.
However, I am not sure if I understand 100% why.
This is how I think. Let us imagine we have SingleLinkedList with 5 Nodes and we put in the first Node in the private method to reverse it.
Since n isnt null, its the first node. It will enter the if statement.
It will call on itself, but now with Node second, its not null since it will repeat....
Now it reaches Node 5, it calls itself, but then it will call on reversed (six,b) since Node six dosent exist and is null, it will not work. Therefore it moves to the row "b.append(n.element);" however. It now remembers where it started and appends "first.element"; after that it will append a new row.
What exaplins the logic that it will hereafter append second.element; Can someone explain how I should think to understand that it will now append the second element?
Thanks in advance, think I really need to understand this to under recursion fully in java
Each method call keeps its own state. Once you get to node 6, there will be 5 calls on the stack waiting for reversed(n.next, b) to finish. Each method can only continue after the call to reversed on the stack above it finishes.
In this example you have last in as the first to act, i.e. you have a non-tail recursive function (the recursive call is happening before you perform the action of that method).
Imagine if every time you got to reversed you replaced that method call with the code it would execute. Remember all the calls happens serially (there is only one thread, nothing can happen in parallel). You'd get something that looks like this:
if (n0 != null) {
Node<E> n1 = n0.next;
if (n1 != null) {
Node<E> n2 = n1.next;
if (n2 != null) {
Node<E> n3 = n2.next;
if (n3 != null) {
Node<E> n4 = n3.next;
if (n4 != null) {
Node<E> n5 = n4.next;
if (n5 != null) {
// would be null so nothing happens
}
b.append(n4.element);
b.append('\n');
}
b.append(n3.element);
b.append('\n');
}
b.append(n2.element);
b.append('\n');
}
b.append(n1.element);
b.append('\n');
}
b.append(n0.element);
b.append('\n');
}
You can see how this code gets pretty hard to read once the number of elements goes up. When we don't know exactly how long the list will be this approach breaks down... you wouldn't want to do this 10, 100, or possibly thousands of times!
This is exactly why recursion is so useful for applications like this. We are able to re-use the interesting logic without having to know the length of the list, and are able to reduce duplicated code significantly.
Just keep in mind that recursion comes at a memory cost. Each time you enter the recursive method you add state to the stack. Once you cap out the memory on your machine you'll have to begin looking at non recursive ways of performing this work.

Remove duplicates in list from Cracking the Coding Interview

From Cracking the Coding Interview.
Problem 2.1: Write code to remove duplicates from an unsorted linked list.
This is the solution that they provide:
public static void removeDuplicates(Node n) {
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
Node previous = n;
while (n != null) {
if (table.containsKey(n.data)) {
previous.next = n.next;
} else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
My question is:
When you do n=n.next, wouldn’t you lose the head of the list (first node)?
How would you access to this list again with the duplicates removed if you don’t have access to the head?
And also isn’t it better to use a Set instead of a Table?
I don’t think you need Key and Value. I think you only need the Key, right?
Thank you
First, as already mentioned in a comment, the change of the local parameter has no effects to the callers input-variable.
Second, you are right, using a Set would be better, but only because the code is better to read. The code is syntactically correct, internally a Set is nothing else than a Map with the same
dummyobject as value for every key.
There is no return statement in the function, as it is set as void.
However, if the head of the list is kept outside of the function in some variable, it is enough to return the correct result.
That's because the first node is not going to be removed, as there will not be any duplicate at this time.
After all, you don't have any problem with changing the n value.

Java do while loop to for each or for loop

I'm pretty new to Java and trying to figure out how I would convert the below code
to a for loop or a for each loop.
do {
testPages.push(testParentPage);
if(homePage != null && testParentPage.getPath().equals(homePage.getPath())){
isParent = true;
break;
}
} while((testParentPage = testParentPage.getParent()) != null);
Any help is greatly appreciated! Thanks!
It can be rewritten in a for loop like this:
for (; testParentPage != null; testParentPage = testParentPage.getParent()) {
testPages.push(testParentPage);
if(homePage != null && testParentPage.getPath().equals(homePage.getPath())){
isParent = true;
break;
}
}
Thought I must admit that I don't know if it serves any benefit.
Try
for(; testParentPage != null; testParentpage = testParentPage.getParent()) {
...
}
The for loop structure is (variable initialization; boolean test; assignment) - usually the variable is an integer, the test is a < or >, and the assignment is an increment, but this doesn't need to be the case.
Actually the do .. while loop looks to be perfectly appropriate in this case. A for or foreach loop would be the tool of choice if you have a "normal" collection or something giving you an iterator. But in this case (navigating a tree structure upward) using a for loop would IMHO actually be confusing.
In addition to that, the condition of a for loop is always evaluated before execution of the loop body. Since you need to execute the body at least once this would make things more difficult and/or complex.
Edit: Of course it might actually make sense to perform the null-ness check at the beginning of the loop, since you call a method on testParentPage in the loop body.
Re: for-each loop.
A for each loop iterates over a Collection or array (see docs) so you won't be able to (immediately) convert your do-while loop to a for-each loop, since you're iterating over a custom-defined hierarchy.
If you had a List<TestPageParent> (or whatever the type name is for that) it would work. So would TestPageParent[]. Or Collection<TestPageParent>.

Java is not assigning values to my variables correctly, with linked lists

public void returnRental(Customer cust){
Rental toDelete = null; //Rental to be removed from list.
LinkedList<Video> toReturn = null; //List of videos to be added to inventory.
//Find appropriate rental according to customer name.
for(int i = 0; i < rentals.size(); i++){
if(cust.getName() == rentals.get(i).getRentee().getName()){
toReturn = rentals.get(i).getRented();
toDelete = rentals.get(i);
}
}
here is the snippet of code that is giving me problems. I've debugged it in eclipse quite a bit which ended up just confusing me more. It hits the if, and passes the condition. But once it gets to assigning values to "toReturn" it assigns it an empty list with size 0. Where as I check my rentals Linked list and the correct value are there, but for some reason it is not getting assigned to my variables correctly :( The same happens to "toDelete" but this isn't a list, it is one instance of my class Rental. (The linked list is a list of rentals, which contains a linked list of videos)
No errors are thrown...
Its a little difficult to explain, if you need more information please let me know and i'll clarify.
I'm at a loss, possibly because I'm not iterating through my linked list correctly?
Replace
if (cust.getName() == rentals.get(i).getRentee().getName()){
by
if (cust.getName().equals(rentals.get(i).getRentee().getName())){
You can't compare strings with == (except if your algorithm can ensure this is the same instance, which is almost never the case).
But the missing equals is not the only bug. It may be inside getRented() or elsewhere (you don't show what you do with toReturn and toDelete, so it's not clear if you don't have problems here).
Now, to go on chasing your bugs, you should either
debug, and put a breakpoint in your loop to check the state of rentals.get(i) and the execution at this point
if you can't debug, put a lot of System.println, so that you know what you have...
I've upvoted dystroy's answer because incorrect string comparison is always wrong.
But because that would fail differently (customer names not matching rentee names), I'm wondering if your issue is really caused by either of the following:
a problem in getRented(); or
cust having a null name on call, which would match a Rentee with a null name.
Possibly, your if condition is being hit more than once. First of all, check if this is actually happening. If so, check your logic and determine if you want to stop at the first occurence or at the last (this case seems to be the latter).
If you want to stop at the first occurence, break the iteration:
for(int i = 0; i < rentals.size(); i++){
if(cust.getName() == rentals.get(i).getRentee().getName()){
toReturn = rentals.get(i).getRented();
toDelete = rentals.get(i);
break;
}
}
for(int i = 0; i < rentals.size(); i++){
if(cust.getName().equals( rentals.get(i).getRentee().getName())){
toReturn.addAll(rentals.get(i).getRented());
//assumming it returns the list of Video object
toDelete = rentals.get(i);
}
}

Null Pointer Exception in an If statement

Hoping you guys can figure out why im getting a null pointer exception with what I can provide, the program has several classes and method but this is the one that is breaking.
public void search(Node node, String sData, int iData)
{
if (sData.equals(node.getString()) && (iData == node.getInt()))
{
System.out.println("Nailed it");
}else if (sData.compareTo(node.stringData) < 0)
{
search(node.left, sData, iData);
}else if (sData.compareTo(node.stringData) > 0)
{
search(node.right, sData, iData);
}
}
the Node that is getting input at first is the root and then it goes left or right from there through recursion, but the line that says its erroring is the if statement up top. Cannot figure out what is wrong sData is just a standard string input when the method is called and iData is just an int thats input as well. Cannot figure it out =/ thanks for any help
You need to add the following at the top of your method:
if (node == null) return;
This would ensure that the method returns gracefully if you search for something that doesn't exist in the structure. Otherwise with your existing code, you'll encounter NullPointerExceptions when the method encounters leaf nodes.
Two possibilities: either sData or node are null; your recursive calls potentially pass null nodes, that's what I'd start with. I can't really tell more from your code, sorry.
Additionally, consider using a debugger to step through your code if you can't find the error. That usually helps with code like this.

Categories