Here below is a code snippet in java.
Collection contextPages = (Collection) getContextPages();
Iterator contextPageIter = contextPages.iterator();
while (contextPageIter.hasNext()) {
Page contextPage = (Page) contextPageIter.next();
String result = contextPage.getResult(); // <-- Null pointer exception here
// Other stuff which this API does.
}
This code has been in production for a while. But for some reason, we hit a null pointer at String result = contextPage.getResult();.
So looks like even though we did a check for hasNext(), the next() method is returning null.
One possibility is that the collection itself has a null, but is it possible that this code could yield to a null pointer in a multi-threaded environment?
Some collections allow you to add a null, so iter.next will return it and when you use it -> NPE
To demonstrate
#Test
public void testNull() {
Collection<Object> c = new ArrayList<>();
c.add(null);
Iterator<Object> iterator = c.iterator();
Assert.assertTrue(iterator.hasNext());
Object o = iterator.next();
Assert.assertNull(o);
}
So check that you don't add null references to the collection or check for null before using the result of Iterator#next()
Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
result = contextPage.getResult();
}
There should be no difference between single- and multi- threaded applications, just make sure you don't add null.
Better to check for null before using the result of Iterator.next()
Try this -
Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
result = contextPage.getResult();
}
Related
I have the following code:
String a= null
Element element = ...
if(element == null) {
System.out.println("...");
}
a = element.getText();
I got a null pointer exception on this code.
I thought that it would be better to use an if else statement in order to avoid this error.
String a= null
Element element = ...
if(element == null) {
System.out.println("...");
} else {
a = element.getText();
}
Is it a good solution to use the above code to solve the problem or it would be better to manage it another way?
I got a null pointer exception on this code
Yes, because you don't not execute element.getText() if element == null.
Element element = ...
if(element == null) { // This check is irrelevant to...
System.out.println("...");
}
a = element.getText(); // ...whether this statement is executed.
Is it a good solution
It's a solution, because the else isn't executed when element == null.
You might consider inverting the condition, so the "happy" case (the one you want to execute when things are working normally) comes first. But this is not an important difference, functionally.
if(element != null) {
a = element.getText();
} else {
System.out.println("...");
}
You approach is ok since it works and you dont get the NPE anymore.
You could invert the if condition and simplify things like:
String a= null
Element element = ...
if(element != null) {
a = element.getText();
}
This way you do your things in a protected code block and you don't need else part unless you really wanted to print "..."
Yes it is a solution for the reasons already mentioned by the other answers. I want to provide another solution:
String a;
try {
Element element = ...;
a = element.getText();
} catch (NullPointerException e) {
System.out.println("...");
a = null; // Or some other value that can be tested but cannot produce a NPE
}
This would have the same error handling as your if statement, but it has the advantage, that ´element´ cannot be referenced later and produce a NPE somewhere else. This is of course only useful if the String cannot produce a NPE either way and if the Element could actually used later (in other words if the method doesn't end directly afterwards).
I added objects to list however there was overriding problem.How can solve this? I sended 3 value in transactionIdList in my main method.
these three value to send below method, i want to add all results return. However there is only two results return with bsList which are in the ( basvuru != null && !basvuru.isEmpty())) state.
List<ApplicationResult> bsList = new ArrayList();
Application bsDB = new Application();
for (int i = 0; i < transactionIdList.size(); i++) {
List basvuru = session.createQuery("from Application as bsvr where bsvr.transactionId = :var1").setParameter("var1", transactionIdList.get(i)).list();
if (basvuru == null) {
ApplicationResult bss = new ApplicationResult();
bss.setTransactionId(transactionIdList.get(i));
bss.setBasvuruDurum("no value");
bsList.add(bss);
} else if (basvuru != null && !basvuru.isEmpty()){
ApplicationResult bs = new ApplicationResult();
bsDB = (Application) basvuru.get(0);
bs.setTransactionId(bsDB.getTransactionId());
bs.setBasvuruDurum(bsDB.getDurum());
bsList.add(bs);
}
}
The only explanation is that session.createQuery() returns one List that is not null, but is empty.
It is most likely that basvruru at some time is not null but an empty list. In this case, nothing is added to the bsList.
You probably want to update the if clause to basvuru == null || basvuru.isEmpty(), and just use and else.
in List implementation values never get overridden. You must have some other issue. could be basvuru is not null
for (int lstSize = 0; lstSize < obj.size(); lstSize++) {
if (obj.get(lstSize).getCuffSize() == null) {
obj.get(lstSize).setCuffSize("");
}
}
I have an ArrayList, where there are many items which has a value of null, can i set values as empty string, if my items in my List Object holds null value.
For instance:
While looping i am getting cuffSize as null, so i am setting it to empty String. But there are such many items in my Object which needs to be set like this. Is there any better way where can i set all the items in my object holding null value to empty string?
An enhanced for would get rid of all the get() calls:
for (MyObj elem : obj) {
if (elem.getCuffSize() == null) {
elem.setCuffSize("");
}
}
In Java 8 you will be able to do this in a cleaner way using Lambdas, but in Java 7 I don't know of a better way than looping.
Rather than setting many properties from null to empty string later I think its better to initialize those properties inside your class itself to empty String like this:
public class MyClass {
private String cuffSize = ""; // init to empty String here
private String somethingElse = ""; // init to empty String here
...
}
Then even if you don't call setters of cuffSize it will contain an empty String instead of null.
I would suggest you add a method in the class of your object. which do the null->"" logic.
The method could return the object reference, so that you could do it during adding it into your list. something like:
public Obj null2empty(){
field1=field1==null?"":field1;
field2=field2==null?"":field2;
field3=field3==null?"":field3;
....
return this;
}
list.add(obj.null2empty());
also possible to do it in iteration:
for(Obj obj : list) obj.null2empty();
Or you can use iterator:
Iterator<MyObject> it = obj.iterator();
while(it.hasNext())
{
MyObject obj = it.next();
if(obj == null) { .. }
}
The implementation of getCuffSize() method can be below, so that your end objective is met
public String getCuffSize()
{
return (cuffSize == null) ? "" : cuffSize;
}
I have the following code snippet.
Explanation:
I have the array called result.
This array consists of different String attributes like "city", "countryName" and "IATA".
With a for loop, I try to access and retrieve all the aforementioned fields.
My problem now is: While "city" and "countryName" always have a value, "IATA" sometimes does not have a value and thus returning me "null", which leads to the nullPointerException as soon as I access an empty "IATA".
I tried this:
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
But, this if condition is not working as I try to access a field which is null.
Has anyone an idea how I can solve this?
Here is the relevant code snippet:
private String[] startIATA = new String[200]; //That is more than long enough
...
for (int count = 0; count < result.getAirports().length(); count++) {
AirportsEntry entry = result.getAirports().get(count);
// Block for StartAirport
HorizontalPanel hp = new HorizontalPanel();
hp.setSpacing(5);
hp.add(new Label(entry.getCity()));
hp.add(new Label(entry.getCountryName()));
hp.add(new Label(entry.getIATA()));
GWT.log("IATA: " + entry.getIATA());
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
startAirportVP.add(hp);
}
Thank you very much for your time and your help!
Perform a simple null check prior to accessing the property of the object.
if(entry != null && entry.getIATA() != null){
startIATA[count] = entry.getIATA();
}
You cannot use equals method to check for null. Use ==:
if (entry.getIATA () == null)
use this:
if (entry.getIATA() != null)
I trying to find whether the elements of 2 arrayLists are match or not.
But this code give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException since some of the elements are null.
How can I solved this problem?
String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));
String choice []={null,"High","Low","High",null,"Medium"};
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));
//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
if(!(m.get(i).equals(n.get(i)))){
result= true;
break;
}
}
return result;
}
Just use Arrays.equals, like so:
String level []={"High","High","High","High","High","High"};
String choice []={null,"High","Low","High",null,"Medium"};
return Arrays.equals(level, choice);
The problem is that you are calling the equals method on some elements without first checking for null.
Change to:
for(int i=0; i<m.size(); i++){
if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){
result = true;
break;
}
}
Or if you want to allow two null values to compare equal:
for(int i=0; i<m.size(); i++){
if (m.get(i) == null) {
if (n.get(i) != null) {
result = true;
}
} else if(!(m.get(i).equals(n.get(i)))){
result = true;
}
if (result) {
break;
}
}
One thing I don't get - why are you setting result to true when you find a mismatch? Don't you want to return true if both lists match and false otherwise?
The root of this problem could be you are using null as an actual value.
Just looking at your code you could use enum and instead of null use an EMPTY value. Then you can actually compare with in a list without nullpointerexceptions.
Check this out:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
Also try to avoid using arrays. Just use List but use the proper type. Don't use List<Object> that is almost never valid.
null should indicate an error or testing only. It should never be used in valid code as you will create null pointer exception bugs during runtime.
if you know the first list never contains nulls switch the call around
if(!(n.get(i).equals(m.get(i)))){
also specifying ArrayList<Object> is bad practice, use List<String> if it is actually String objects.
Check if the objects are the same object (or both null) first. Check for null before you do the equals() test.
boolean result = true;
String level[] = { "High", "High", "High", "High", "High", "High" };
ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));
String choice[] = { null, "High", "Low", "High", null, "Medium" };
ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));
// Check if the two arrayList are identical
for (int i = 0; i < m.size(); i++) {
String mElement = m.get(i);
String nElement = n.get(i);
if (mElement == nElement) {
result = true;
} else if ((mElement == null) || (nElement == null)) {
result = false;
break;
} else if (!(m.get(i).equals(n.get(i)))) {
result = false;
break;
}
}
return result;
}
Rewrite your if like this in order to check for both double-nullity and single-nullity:
if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))
Rather than solving this specific problem, give yourself a tool you can use over and again, e.g.:
public static final boolean areEqual(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
...in some handy utility class, then use that in your loop.
But of course, for this specific requirement, derivation has the right answer (use java.util.Arrays.equals(Object[],Object[])).
Remove NULLs
You can remove NULL values from your List objects before processing.
myList.removeAll( Collections.singleton( null ) );
The Collections class is a bunch of convenient utility methods. Not to be confused with Collection (singular), the interface that parents List and is implemented by ArrayList.
See this posting, Removing all nulls from a List in Java, for more discussion.