I'm using a method that returns a list that is fetched from a web service. This list sometimes does not contain anything. Which results in "java.lang.IndexOutOfBoundsException"
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
I have used the if statement above to prevent the exception, but it does not work. Is there anyway I can prevent this Exception by using if statements so the program do something else in case the list is empty?
If you want to ensure the list is not null, and, contains at least two elements, do this:
if( placesList != null && placesList.size() >= 2)
The list could be defined, but have no strings in it (an empty list). You should also check the size of the list:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.size() > 1)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
The list object is not null, but the contents inside can be zero
Use placeList.size() to check the number of contents inside.
If ArrayList == null returns true it doesn't mean that it's empty, it means that it hasn't been initialized and it points to null.
In order to check if your list is empty, you can use
if (!placesList.isEmpty()){
}
Just because the ArrayList object is not null, does not imply there are any elements in it.
You can call isEmpty() or size() methods to determine if there are any elements in the array.
Try this:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.isEmpty() == false )
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
Javadoc reference
Check to make sure the ArrayList is not null, then add a second condition ensuring the size is equal to 2 to ensure it contains what you expect
if (placesList != null && placesList.size() == 2)
Try
if (placeList.size() > 1)
you should check length of the arraylist.
something like
if (placesList.size() > 0)
One way to approach this is by:
if(placesList.isEmpty())
{
//do something here when empty
}
else
{
poi = placesList.get(0);
}
Related
I have an array
String [] array = account.getDetails().split(',');
the account details is sometimes null, how to avoid the exception?
I did something like that, but that does not like pretty.
if (account.getDetails() == null)
{
account.setDetails("");
}
String[] array = account.getDetails().split(',');
That avoid throwing the NullPointerException, is this okay or is there a better way?
If you're looking for a "prettier" way of doing it, then this is a spot that seems decent for the '?' operator (called the ternary operator)
String[] array = account.getDetails() == null? new String[]{""} : account.getDetails().split(",");
You could also change the getter or the setter/constructor so that the getDetails() method never returns a null (because it won't or because it never has a null at all).
public String getDetails() {
return details == null? "" : details;
}
Your implementation is fine (more below), but you can avoid calling split(String) on an empty string and do something like this:
String[] array;
if (account.getDetails() == null) {
array = new String[0];
} else {
array = account.getDetails().split(",");
}
Be careful that your implementation would return an array with one empty string if the input was null, this will return an empty array.
As pointed out by #MarkAdelsberger you should not change the value directly on the object, this is known as god behavior.
Null check with if else statement is ok. Also needs to be mentioned that in java8 an Optional was introduced, that help to avoid null checking. With optional it will look like:
String[] strings = Optional.ofNullable(account.getDetails())
.map(s -> s.split(",")).orElse(new String[0]);
So here is the good way in my opinion, first you check if the details is not null using ? if it's not null you just do the split and assign result to variable array, else you assign empty array of strings since details were null:
String details = account.getDetails();
String[] array = details != null ? details.split(",") : new String[0];
Assume I want to check if the first element from a list is equal to "YES" or "NO".
dummy_method(List<String> myList) {
if(myList.isEmpty()) {
return null;
}
String firstListValue = myList.get(0).getStringValue();
// Should I do this:
if ("YES".equalsIgnoreCase(firstListValue)) {
return firstListValue;
}
// OR this:
if (firstListValue.equalsIgnoreCase("YES")) {
return firstListValue;
}
// Do something else
}
In other words: Does the order of if A equals B versus if B equals A matter when I already have a null-check?
Yes. It matters.
You have only checked if the list is non-empty. If the first element in the list is null then you will get a NullPointerException at
firstListValue.equalsIgnoreCase("YES")
But, if you can ensure all the elements (or at least the first element) in the list are non-null, then both the statements are equivalent.
For null safety you can use your first if like this:
if ("YES".equalsIgnoreCase(firstListValue)) {
return firstListValue;
}
because "YES" is hardcoded string and won't be null. Where as in 2nd approach, whenever the list element is null, you will get NullPointerException.
This check will also throw NullPointerException if the list is null, so you can check both conditions
if(myList!=null && !myList.isEmpty())
And also need 'null' check for all values retrieved through 'get()' , because if list is empty or specified index is out of range 'get()' method will not throw 'NullpointerException', it will just return null
I'm checking whether a List object is null or not using java. But I'm not sure whether it is the optimized way or not.
Here is my code:
List<String> listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
The above line itself throws null pointer exception.
if(listSCBPLNewErrMsgs != null) <Right way?>
This will get all the values from the config.
Now, tomorrow if I change the config entry, this should not throw an null pointer exception
The new operator in Java can never return null. Neither can String#split.
What you may want to check, however, is that the list is not empty:
if (listSCBPLNewErrMsgs.isEmpty()) {
// do something
}
If SCBPL_NEW_ERRORMESSAGES is null that code will still fail.
Assuming that SCBPL_NEW_ERRORMESSAGES has some value or is empty, the split will return an array of size 0 or more. Changing it to a list from an array will yield either an array with 0 or more elements.
Lastly, the copy constructor will copy the content and assign it to a new list. In all scenarios, unless there is a null pointer on SCBPL_NEW_ERRORMESSAGES, the returned list (listSCBPLNewErrMsgs) will never be null, at most it will be empty, which can be checked with the isEmpty() method call.
As per your comment, if you are getting a null pointer on that line, it should be due to the fact that SCBPL_NEW_ERRORMESSAGES is null.
Try this:
List<String> listSCBPLNewErrMsgs = null;
if(SCBPL_NEW_ERRORMESSAGES != null) {
listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
}
else {
listSCBPLNewErrMsgs = new ArrayList<>();
}
If you want to check whether it is null it is right way (even though it will never be null), however if you simply want to check if list is empty then you should use isEmpty() method:
if(listSCBPLNewErrMsgs.isEmpty()) {/**/}
From the looks if your code your listSCBPLNewErrMsgs object won't be null. Test if it is empty using the listSCBPLNewErrMsgs.isEmpty();
If SCBPL_NEW_ERRORMESSAGES is nulll that will throw a NPE exception indeed since you will be using the split method on null.
You can first check if that's not null:
if (SCBPL_NEW_ERRORMESSAGES != null) {
//Instantiate list
//Optional isEmpty check
}
You will first check if SCBPL_NEW_ERRORMESSAGES is not null
Then you can instantiate your list and perform an optional isEmpty check on the new list.
if(SCBPL_NEW_ERRORMESSAGES != null)
List<String> listSCBPLNewErrMsgs= new ArrayList<String>Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
No Need of listSCBPLNewErrMsgs != null as everyone said
First you have to check SCBPL_NEW_ERRORMESSAGES is null or empty
if(!TextUtils.isEmpty(SCBPL_NEW_ERRORMESSAGES))
You have to check both whether the list is null/empty or not. So I prefer
if(listSCBPLNewErrMsgs != null && !listSCBPLNewErrMsgs.isEmpty()) {
}
You need to add null check for SCBPL_NEW_ERRORMESSAGES.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
In your declaration, list can not be null as your are doing new ArrayList<String>.
So no need to worry about null pointer exception.
If you wish to check for empty list.
Then you can try isEmpty() method.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
List<String> listSCBPLNewErrMsgs = new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
if (!listSCBPLNewErrMsgs.isEmpty()) {
// Do something.
}
}
I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))
I am having an issue in getting the data in the below loop ,even though the size is not zero i am getting null in the sysout 'data is'.What is wrong there ?
List<Long> dd = domainItemMapper.getIsSearchable(34372);
System.out.println("the test is-" + dd.size());
for (int i = 0; i < dd.size(); i++) {
Long isSearch = dd.get(i);
System.out.println("data is"+dd.get(i));
if (isSearch.equals(0)) {
isSearchValue = false;
} else
isSearchValue = true;
}
The call to database is a mybatis call as below
interface
List<Long> getIsSearchable(#Param("parentFieldId") long parentFieldId);
impl
<mapper namespace="com.ge.dbt.common.persistence.IFormValidatorMapper">
<select id="getIsSearchable" statementType="CALLABLE"
resultType="Long">
select is_searchable from t_field where parent_field_id=#{parentFieldId}
</select>
</mapper>
I guess your whole code can be converted in to two lines.
if(dd!= null && !dd.isEmpty())
return dd.contains(0);//Contains Guard you in such cases because equals check
//happen on passed element ie *0*
Default value of Long in java is null. So you will need additional check for null in your case.
Enclose your isSearch.equals check in a null check
if(isSearch != null)
{
if (isSearch.equals(0))
{
isSearchValue = false;
}
else
{
isSearchValue = true;
}
}
However it'll be better to modify code for domainItemMapper.getIsSearchable(34372); method so that it doesn't fill the list with null at all.
Seems to be your list contains null literals. And List Supports null as a value.
based on your this comment
The data has null,0 and 1 data.I want to return data only for 0 and 1.
You need to fix your query like this
select is_searchable from t_field where parent_field_id=#{parentFieldId} and is_searchable is not NULL;