Some fields in a Java array are null, handling of these - java

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)

Related

adding object to list overwrite some results

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

Java String array: how do I check if the array has a value?

I'm making a program in java that will use a string array say:
String[] category = new String[46];
Then I will check if the array in a for loop if it already has a value,
for(int checking = 21; checking <= 45 ;checking++) {
if(category[checking]=INSERT_HERE) {
textArea += category[checking] + "\n";
}
}
What do I put in INSERT_HERE? Note: textArea is a named JTextArea.
If you are making a check if the value is not null, then use
if(category[checking]!=null)
And if you are making a check for some particular value, then
if(category[checking].equals(PARTICULAR_VALUE))
PS: '=' is for assignment, you should use '==' for comparison.
u have to checkout if it is not null use like this:
if(category[checking] != null) // will check all filled values only
When you define your array as
String[] category=new String[46];
you allocate 46 reference slots in memory for your array. These slots are initially null, so when you need to do a comparison like the one you asked, you need to check against null.
...
if(category[checking] != null)
...
You could try something like that in your code:
for(int checking=21;checking<=45;checking++) {
if(category[checking] != null) {
textArea+=category[checking] +"\n";
}
}
Or like that:
for(int checking=21;checking<=45;checking++) {
if(category[checking] != "") {
textArea+=category[checking] +"\n";
}
}
for(int checking=21;checking<=45;checking++) {
if(category[checking] != null || category[checking] != "") {
textArea += category[checking] +"\n";
}
}

Data getting overwritten in for loop for new and previous values

I want tov compare previous and new value coming from a loop and based on data increment some rows.For that i am doing like below but the data is getting overwritten since i am doing inside for loop.How can i perform this.
for (RecordData recordData : recordDataList) {
prevRespondentId = recordData.getRespondentId();
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
I have data like 1,2,3 as respondent Id ,i need to see new and prev based on that increment data.
Would this fix your issue?
prevRespondentId = recordDataList.get(0).getRespondentId(); //Initialize to first or default value probably -1?
for (RecordData recordData : recordDataList) {
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
Basically you are overwriting the prevRespondentId even before checking for it, which is causing the issue.
Difficult to understand what your trying to do however perhaps something like this:
for (RecordData recordData : recordDataList) {
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
Basically don't override the preRespondentId until you've done your if check. This will ensure that it will always be the previous respondent id. You'll of course need to initialise it though.
Hope that helps.
..some type.. prevRespondentId = -1;
for (RecordData recordData : recordDataList) {
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}

NullPointerException and the best way to deal with it

Note: This is homework/assignment feel not to answer if you don't want to.
Ok after some search and reading these:
How to check if array element is null to avoid NullPointerException in Java
Gracefully avoiding NullPointerException in Java
http://c2.com/cgi/wiki?NullPointerException
Am still not making any progress on how to deal with NullPointerException error on my code, snippet for questionable code:
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem != -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
} else { System.out.println("Element " + newValue + "already exist"); }
}
It compile but adding new element to a set throws a NullPointerException error.
D:\javaprojects>java SetDemo
Enter string element to be added
A
You entered A
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:31)
at Set.add(Set.java:44)
at SetDemo.main(Set.java:145)
I added another check, though honestly don't have clue if this right to line 31.
if ( setElements != null && setElements[i].equals(element) ) but still no joy.
A documentation/tips or explanation is greatly appreciated.
learning,
lupin
Did you initialize setElements anywhere? Meaning:
String[] setElements = new String[100];
If you simply declare an array variable:
String[] setElements;
as a data member of your class it is initialized to null. You have to make it point to something. You can either do this inline:
public class MyClass {
private String[] setElements = new String[100];
...
}
or in a constructor:
public class MyClass {
private String[] setElements;
public MyClass() {
setElements = new String[100];
}
...
}
The for-loop in findElement doesn't make sense.
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
You should iterate through all values before returning -1, only then do you know that there is no element in the set that matches element.
Post the entire class - this snippet is useless.
You're making two serious mistakes: failing to believe the compiler, and assuming that your code is correct.
If the JVM tells you that line 31 is the problem, believe it.
My guess is that setElements[i] is null.
It should be setElements[i] != null && setElements[i].equals(element). If a collection contains null elements you will try to dereference a null reference when you call equals method on that element.
As for NullPointerException - you should never catch it. For things that shouldn't be null, they must be initialized properly. For those things that cannot be null - they must be checked for null before dereferencing them (i.e. calling methods on them).
The only use case for catching NullPointerException is when you are using a third-party library that you don't have the source for and has a bug that causes NullPointerException to be thrown. These cases are rare and since you only beginning to learn Java, forget that I mentioned this and concentrate on more important things.
Try testing the element itself for null, not the array:
setElements[i] != null && setElements[i].equals(element)
You should not attempt to catch a null pointer exception. Instead, the best way to avoid null pointers is:
In any function that takes parameters where you assume that the parameter is non-null, always check that the parameter is non-null and throw an IllegalArgumentException if it is null.
Whenever you invoke a function that does not allow null parameters, ensure that you do not pass a null pointer to that function; if you already know that the object is non-null (because you already checked it and would have thrown an IllegalArgumentException), then you do not need to recheck; otherwise, you should double-check that the object is non-null before passing it along.
Since you do not check the parameters to your findElement and add functions, it is quite possible that the parameters are the culprits. Add the appropriate check and throw IllegalArgumentException if they are null. If, after you do that, you get an IllegalArgumentException, then you've solved your problem. If not, then you at least know that the problem is not the parameter and is elsewhere in the code.
Its working now, thanks to Lars,Igor and the rest who took time to critic the code, there's a logic error that wasn't check,anyway here's the corrected working code, lastly I'm bother am I doing cheating? :(
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) { //loop first to the array and only return -1 once we can't find it.
//setElements[i] != null is the NullPointerException killer :)
if ( setElements[i] != null && setElements[i].equals(element) ) {
return retval = i;
}
retval = -1;
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem == -1 ) { # == instead of != as I only need to add if elements is non-existing
setElements[numberOfElements] = newValue;
numberOfElements++;
}
}
with thanks,
lupin

How to avoid null pointer error

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.

Categories