My Java program regarding Stacks made from LinkedLists. The task at hand was to merge two sorted stacks into one. I think I figured it out but it won't show any output and also it doesn't terminate. Can anyone help?
The "next" instance is pointing to the LinkedList's next element's address in the memory.
void mergeStacks()
{
Stacks sortedMain = new Stacks();
Stacks sorted1 = new Stacks();
Stacks sorted2 = new Stacks();
sorted1.push(1);
sorted1.push(2);
sorted1.push(3);
sorted2.push(4);
sorted2.push(5);
sorted2.push(6);
System.out.println("Stack 1");
sorted1.displayStack();
System.out.println("Stack 2");
sorted2.displayStack();
Node q = sorted1.head,p = sorted2.head,x = sortedMain.head;
while(q.next != null)
{
if(x == null)
{
sortedMain.push(sorted1.pop());
}
while(x.next != null)
{
sortedMain.push(sorted1.pop());
x = x.next;
}
q = q.next;
}
while(p.next != null)
{
while(x.next != null)
{
sortedMain.push(sorted2.pop());
x = x.next;
}
p = q.next;
}
System.out.println("Merged Stack\n");
sortedMain.displayStack();
}
So, I figured out the thing that is causing the console to not show anything. Apparently, the function "pop()" is not really returning int for some reason. Here's the method:
int pop()
{
int popped = 0;
if(isEmpty())
{
System.out.println("Stack is empty");
}
else
{
Node q = head;
while(q.next != null)
{
if(q.next.next == null)
{
popped = q.data;
q.next = null;
top = q;
}
}
}
return popped;
}
Output(With Debugger)
You have this inside the first while loop, which makes no sense:
if(x == null)
{
sortedMain.push(sorted1.pop());
}
while(x.next != null)
{
sortedMain.push(sorted1.pop());
x = x.next;
}
When x is null in the first if statement, how can you then use it in the next while statement? That should produce a null reference exception...
It seems like maybe you think that x would be somehow updated to the new head when you push something into an empty sortedMain? It won't be.
Also, is the "merged" stack supposed to be sorted? Your code appears to be trying to simply push all of the first sorted stack in, followed by pushing all of the second sorted stack in. This may or may not result in an overall sorted stack...depends on the elements within.
What I think should happen is you pop just the first two from each list and do a comparison, pushing whatever is greater/smaller (you didn't specify a sort order). Then you pop the next one from the side that was pushed and repeat. If one side becomes empty, then you'd simply push all the rest from the other side.
From the comments:
I don't really have to define an order in what they are going to
merge. I just want to merge them in whatever order they are into a
third stack. My strategy is to traverse through the first stack and
push all the elements into the main stack and do the same with the
next one.
Did you implement an isEmpty() method for your Stacks class? If so, this is what most people would expect to see:
while(!sorted1.isEmpty())
{
sortedMain.push(sorted1.pop());
}
while(!sorted2.isEmpty())
{
sortedMain.push(sorted2.pop());
}
If you haven't implemented an isEmpty() type method, then you could check to see if the head is null instead? (*I'm assuming you correctly set that to null when the stack is empty!):
while(sorted1.head != null)
{
sortedMain.push(sorted1.pop());
}
while(sorted2.head != null)
{
sortedMain.push(sorted2.pop());
}
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.
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);
...
I am in a beginning class for programming and try to combine 2 lists to make one list, putting the new list in numerical order. The part I am having trouble with is, allowing the code to loop, repeating the steps so that it runs through the total original loops to complete the final list which is a combination of all the numbers from the original lists. Any guidance for the loop would be appreciated. Thank you.
import inClass.list.EmptyListException;
import inClass.list.List;
public class InitialLists {
public static void main(String[] args) {
List<Integer> intObject1 = new List<Integer>();{
intObject1.insertAtFront(25);
intObject1.insertAtFront(19);
intObject1.insertAtFront(3);
intObject1.print();}
List<Integer> intObject2 = new List<Integer>();{
intObject2.insertAtFront(120);
intObject2.insertAtFront(1);
intObject2.print();}
List<Integer> combinedList = new List<Integer>();
int object1 = intObject1.removeFromBack();
int object2 = intObject2.removeFromBack();
while(intObject1.removeFromBack() != null && intObject2.removeFromBack() != null){
try {
{
if (intObject1.removeFromBack() > intObject2.removeFromBack()) {
combinedList.insertAtFront(object2);
intObject1.insertAtBack(object1);
}
else if (intObject2.removeFromBack() < intObject1.removeFromBack()) {
combinedList.insertAtFront(object1);
intObject2.insertAtBack(object2);
}
else if (intObject1.removeFromBack() == intObject2.removeFromBack()) {
combinedList.insertAtFront(object1);
}
}
combinedList.print();
object1 = intObject1.removeFromBack();
object2 = intObject2.removeFromBack();
} // end try
catch (EmptyListException emptyListException) {
emptyListException.printStackTrace();
} // end catch
} //end while
} // end main
}// end class
What about:
List<Integer> combinedList = new ArrayList<Integer>();
combinedList.addAll(intObject1);
combinedList.addAll(intObject2);
Collections.sort(combinedList);
Or am I missing something?
To merge two files / lists / streams you need a loop that looks a bit like this
WHILE NOT FINISHED
GET SMALLEST VALUE FROM INPUTS
APPEND SMALLEST VALUE TO OUTPUT
So how will you know that you are finished?
How will you get the smallest of the next item in each list?
The code I have written above is called pseudocode; it is a way of describing the steps of an algorithm. Keep expanding each step until you have pseudocode that you can implement in your chosen language, in this case Java.
Hope that helps ...
I guess your problem is because of possible uneven size of two lists. Try putting while condition as below:
Integer object1 = intObject1.removeFromBack();
Integer object2 = intObject2.removeFromBack();
while(object1 != null || object2!= null){
if(object1 ==null){
//safe to assume object2 is not null as both not null together (that is the termination condition)
combinedList.insertAtFront(object2);
}else if(object2 ==null){
//safe to assume object1 is not null as both not null together (that is the termination condition)
combinedList.insertAtFront(object1);
}else{
//put you normal condition of handling object1 and object2 being not null
if (object1.intValue() > object2.removeFromBack()) {
combinedList.insertAtFront(object2);
intObject1.insertAtBack(object1);
}
else if (object2.intValue() < object1.intValue()) {
combinedList.insertAtFront(object1);
intObject2.insertAtBack(object2);
}
else if (object1.intValue() == object2.intValue()) {
combinedList.insertAtFront(object1);
}
}
object1 = null;
object2 = null;
try{
object1 = intObject1.removeFromBack();
}catch (EmptyListException emptyListException) {
//do nothing
} // end catch
try{
object2 = intObject2.removeFromBack();
}catch (EmptyListException emptyListException) {
//do nothing
} // end catch
}
Also please note: There are better way of doing the merge of two sorted list elements. This approach is advised in light of your little known custom List class.
Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.
So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
No, can't change the structure. It's from a service I don't have control over.
No, I can't use Groovy and it's handy "Elvis" operator.
No, I'd prefer not to wait for Java 8 :D
I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.
You can use for:
product.getLatestVersion().getProductData().getTradeItem().getInformationProviderOfTradeItem().getGln();
optional equivalent:
Optional.ofNullable(product).map(
Product::getLatestVersion
).map(
ProductVersion::getProductData
).map(
ProductData::getTradeItem
).map(
TradeItemType::getInformationProviderOfTradeItem
).map(
PartyInRoleType::getGln
).orElse(null);
Your code behaves the same as
if(family != null &&
family.getPeople() != null &&
family.people.get(0) != null &&
family.people.get(0).getAddress() != null &&
family.people.get(0).getAddress().getPostalCode() != null) {
//My Code
}
Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.
If, in case, you are using java8 then you may use;
resolve(() -> people.get(0).getAddress().getPostalCode());
.ifPresent(System.out::println);
:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
REF: avoid null checks
The closest you can get is to take advantage of the short-cut rules in conditionals:
if(family != null && family.getPeople() != null && family.people.get(0) != null && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
By the way, catching an exception instead of testing the condition in advance is a horrible idea.
I personally prefer something similar to:
nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))
public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
try {
function.apply(supplier.get());
} catch (NullPointerException n) {
return null;
}
}
or something like
nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())
public static <T> T nullSafeGetter(Supplier<T> supplier) {
try {
return supplier.get();
} catch (NullPointerException n) {
return null;
}
}
Best part is the static methods are reusable with any function :)
You can get rid of all those null checks by utilizing the Java 8 Optional type.
The stream method - map() accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the neath.
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
We also have another option to achieve the same behavior is by utilizing a supplier function to resolve the nested path:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
How to invoke new method? Look below:
Outer obj = new Outer();
obj.setNested(new Nested());
obj.getNested().setInner(new Inner());
resolve(() -> obj.getNested().getInner().getFoo())
.ifPresent(System.out::println);
Instead of using null, you could use some version of the "null object" design pattern. For example:
public class Family {
private final PersonList people;
public Family(PersonList people) {
this.people = people;
}
public PersonList getPeople() {
if (people == null) {
return PersonList.NULL;
}
return people;
}
public boolean isNull() {
return false;
}
public static Family NULL = new Family(PersonList.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
import java.util.ArrayList;
public class PersonList extends ArrayList<Person> {
#Override
public Person get(int index) {
Person person = null;
try {
person = super.get(index);
} catch (ArrayIndexOutOfBoundsException e) {
return Person.NULL;
}
if (person == null) {
return Person.NULL;
} else {
return person;
}
}
//... more List methods go here ...
public boolean isNull() {
return false;
}
public static PersonList NULL = new PersonList() {
#Override
public boolean isNull() {
return true;
}
};
}
public class Person {
private Address address;
public Person(Address address) {
this.address = address;
}
public Address getAddress() {
if (address == null) {
return Address.NULL;
}
return address;
}
public boolean isNull() {
return false;
}
public static Person NULL = new Person(Address.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
etc etc etc
Then your if statement can become:
if (!family.getPeople().get(0).getAddress().getPostalCode.isNull()) {...}
It's suboptimal since:
You're stuck making NULL objects for every class,
It's hard to make these objects generic, so you're stuck making a null-object version of each List, Map, etc that you want to use, and
There are potentially some funny issues with subclassing and which NULL to use.
But if you really hate your == nulls, this is a way out.
Although this post is almost five years old, I might have another solution to the age old question of how to handle NullPointerExceptions.
In a nutshell:
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
}
Since there is a lot of legacy code still in use, using Java 8 and Optional isn't always an option.
Whenever there are deeply nested classes involved (JAXB, SOAP, JSON, you name it...) and Law of Demeter isn't applied, you basically have to check everything and see if there are possible NPEs lurking around.
My proposed solution strives for readibility and shouldn't be used if there aren't at least 3 or more nested classes involved (when I say nested, I don't mean Nested classes in the formal context). Since code is read more than it is written, a quick glance to the left part of the code will make its meaning more clear than using deeply nested if-else statements.
If you need the else part, you can use this pattern:
boolean prematureEnd = true;
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
prematureEnd = false;
}
if(prematureEnd) {
System.out.println("The else part");
}
Certain IDEs will break this formatting, unless you instruct them not to (see this question).
Your conditionals must be inverted - you tell the code when it should break, not when it should continue.
One more thing - your code is still prone to breakage. You must use if(family.getPeople() != null && !family.getPeople().isEmpty()) as the first line in your code, otherwise an empty list will throw a NPE.
If you can use groovy for mapping it will clean up the syntax and codes looks cleaner. As Groovy co-exist with java you can leverage groovy for doing the mapping.
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
instead you can do this
if(family?.people?[0]?.address?.postalCode) {
//do something
}
or if you need to map it to other object
somobject.zip = family?.people?[0]?.address?.postalCode
Not such a cool idea, but how about catching the exception:
try
{
PostalCode pc = people.get(0).getAddress().getPostalCode();
}
catch(NullPointerException ex)
{
System.out.println("Gotcha");
}
If it is rare you could ignore the null checks and rely on NullPointerException. "Rare" due to possible performance problem (depends, usually will fill in stack trace which can be expensive).
Other than that 1) a specific helper method that checks for null to clean up that code or 2) Make generic approach using reflection and a string like:
checkNonNull(family, "people[0].address.postalcode")
Implementation left as an exercise.
I was just looking for the same thing (my context: a bunch of automatically created JAXB classes, and somehow I have these long daisy-chains of .getFoo().getBar().... Invariably, once in a while one of the calls in the middle return null, causing NPE.
Something I started fiddling with a while back is based on reflection. I'm sure we can make this prettier and more efficient (caching the reflection, for one thing, and also defining "magic" methods such as ._all to automatically iterate on all the elements of a collection, if some method in the middle returns a collection). Not pretty, but perhaps somebody could tell us if there is already something better out there:
/**
* Using {#link java.lang.reflect.Method}, apply the given methods (in daisy-chain fashion)
* to the array of Objects x.
*
* <p>For example, imagine that you'd like to express:
*
* <pre><code>
* Fubar[] out = new Fubar[x.length];
* for (int i=0; {#code i<x.length}; i++) {
* out[i] = x[i].getFoo().getBar().getFubar();
* }
* </code></pre>
*
* Unfortunately, the correct code that checks for nulls at every level of the
* daisy-chain becomes a bit convoluted.
*
* <p>So instead, this method does it all (checks included) in one call:
* <pre><code>
* Fubar[] out = apply(new Fubar[0], x, "getFoo", "getBar", "getFubar");
* </code></pre>
*
* <p>The cost, of course, is that it uses Reflection, which is slower than
* direct calls to the methods.
* #param type the type of the expected result
* #param x the array of Objects
* #param methods the methods to apply
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T[] apply(T[] type, Object[] x, String...methods) {
int n = x.length;
try {
for (String methodName : methods) {
Object[] out = new Object[n];
for (int i=0; i<n; i++) {
Object o = x[i];
if (o != null) {
Method method = o.getClass().getMethod(methodName);
Object sub = method.invoke(o);
out[i] = sub;
}
}
x = out;
}
T[] result = (T[])Array.newInstance(type.getClass().getComponentType(), n);
for (int i=0; i<n; i++) {
result[i] = (T)x[i];
}
return result;
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
and my favorite, the simple try/catch, to avoid nested null checks...
try {
if(order.getFulfillmentGroups().get(0).getAddress().getPostalCode() != null) {
// your code
}
} catch(NullPointerException|IndexOutOfBoundsException e) {}