Check if element in object is null - java

I have a simple dataset class similar to:
class DataSet {
private String value;
private String additionalValue;
public DataSet(String value, String additionalValue) {
this.value = value;
this.additionalValue = additionalValue;
}
public String getAdditionalValue() {
return this.additionalValue;
}
}
Then I have created an ArrayList<DataSet> and added a new element DataSet("Value1", null).
Now at some point I need to check if the entry with value "Value1" has additionalValue and if it does, what it is.
I do a simple loop checking if value.equals("Value1") == true, then I do:
if (element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
However, as soon as it gets to the if statement, it throws an error saying that the value is null.
How can I make it so that it doesn't throw an error and just skips the return statement if additionalValue is null?
EDIT:
But the thing is that the element cannot be null at the point where it checks additionalValue as it passed through the element.getValue.equals("Value1") condition.
for (DataSet element : dataSet) {
if (element.getValue.equals("Value1")) {
if (element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
}
}

I think the problem is that your element object is null, so you have to check it before checking additionalValue.
if (element != null && element.getAdditionalValue() != null){
return element.getAdditionalValue();
}

This will sort you out:
if (element != null && element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}

Related

Java - getMethod null check

I have a class as below, before I set the data I need to check whether getValue() is present and it's value is empty.
public class Money {
{
private String value;
private String currency;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getCurrency() {
return currency;
public void setCurrency(String currency) {
this.currency = currency;
}
}
//JSON is like this
"money": {
"currency": "USD",
"value": ""
}
I want to check whether this getValue() is present or not like obj.getMoney().getValue() != null,
and then I need to check it's value is empty... obj.getMoney().getValue().equals("") but it fails on this condition obj.getMoney().getValue() != null as null.
If the following check fails
if (obj.getMoney().getValue() != null) { ... }
then it implies that the money object itself is null. In this case, you can slightly modify your if condition to check for this:
if (obj.getMoney() != null && obj.getMoney().getValue() != null) { ... }
You said that first you need to check whether value is null or not and then also check whether the value is empty or not,
You can do the following
if (obj.getMoney() != null && obj.getMoney().getValue() != null && !obj.getMoney().getValue().isEmpty()) {
// rest of the code here
}
obj.getMoney().getValue() will give you null pointer exception. You should check for null object before using . after it. Example code:
Below code looks huge but it's actually readable and it will be optimized by compiler.
if(obj != null){
Money money = obj.getMoney();
if(money != null) {
String value = money.getValue();
//Add you logic here...
}
}
I think you are getting null point exception. You are facing this exception because obj.getMoney() is already null. Since you are trying to get a null object's value, so you are getting this exception. Correct code will be
if ((obj.getMoney() != null) && (obj.getMoney().getValue().trim().length() > 0)) {
// Execute your code here
}
When instantiating your obj, gives a new. The form of validation is correct, the problem is in the obj that was not initialized. (I believe)

How to check if Iterator.next() is == null?

How do I check if the next element in the list is null ?
while(it.hasNext()){
System.out.println(it.next()+"\n");
}
this is how I tried, but when the last element is null it prints it as null.
I tried to change it
while(it.hasNext()){
if(it.next()==null){
}else
System.out.println(it.next()+"\n");
}
but this just makes it worst because some of the elements don't even print!
This is my Iteration method/anonymous class
public Iterator<Filmi> iterator3DFilms ()throws FilmiException{
if(filmList.isEmpty())
throw new FilmiException("No Films on the list");
return new Iterator<Filmi>(){
private int index=0;
public boolean hasNext(){
return index <filmList.size();
}
public Filmi next(){
Filmi lb = filmList.get(index++);
if(lb.is3D()== true)
return lb;
if(hasNext())
return next();
return null;
}
public void remove(){}
};
}
The null print only happens at the last element
Thank you.
Naturally, code like
if (it.next() == null){
} else {
System.out.println(it.next()+"\n");
}
will consume every other non-null element, as you are observing. Plus calling it.next() without checking it.hasNext() is a recipe for disaster.
Why not write
Foo/*ToDo - use the correct type here*/ foo = it.next()
if (foo != null){
/*ToDo*/
}
instead?
No it cannot work this way because if it.next() is not null you call it.next() twice which will make you skip a value that could not even be available.
Use a variable instead as next:
Object o = it.next();
if (o != null) {
...
}
you should use stream instead of iterator.
filmList.stream().filter(film->film!=null).filter(film->film.is3D())
Edit:
or, if you'r not in Java 8 :
Predicate<Film> isNotNullAnd3D = new Predicate<Person>() {
public boolean apply(Film f) {
return f != null && f.is3D();
}
};
Collection2.filter(filmList, isNotNullAnd3D)
You never mentioned why you use iterators explicitly in the first place.
Why not use implicit iterator notation like this ? :
for (Film film : filmList) {
if (film != null ){
....
}
}
Additionally to what others said: in case you are doing a for-each loop with a primitive type like int
for (int node : input) {
doSomething(node);
}
you might want to consider using the Wrapper class instead:
for (Integer node : input) {
if (node == null) throw new IllegalArgumentException();
doSomething(node);
}

Return a value present in loop in java

I want to return a value from the loop.
My code is as follows:
public long findLocationId(String location) throws SystemException
{
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
**return locId;**
}
}
}
When I try to put the return value in loop I get an error saying to include a return statement.
How should I change my code so that I can return a value from the loop itself?
I want to return the new locId value which I get in the loop and not the value which I set initially as locId = 1;
I want to return the new value of locId which i get from the loop
There are various approach to this problem.
Use while loop
Use for loop with additional stop condition
Use break key word.
Let first create a template before introduce our logic:
public long findLocationId(String locationName) throws SystemException
{
if(locationName == null) { //Here we cover first issue.
throw new IllegalArgumentException("THe locationName must not be null");
}
long locId = Long.MIN_VALUE; //We declare a default value that will be returned if none match found.
Collection<Location> locationList = getLocationList(); //The location can be read from another method so we are not binded to field.
if(locationList == null || locationList.isEmpty()) {
return locId; // Or throw an exception about invalid state.
}
//Place for the logic
return locId;
}
Typically when we do not know when we want to stop the iteration, it is a sign that we should start with while loop.
So lets try it.
Solution 1 - The while way.
Iterator<Location> iterator = locationList.iterator();
while(iterator.hasNext() && Long.MIN_VALUE != locId) {
Location location = iterator.next();
if(locationName.equalsIgnoreCase(location.getLocationName())) {
locId = location.getLocationId(); // This will change the locId, so second condition will be no longer true and loop will end.
}
}
The pros:
- It works
The cons:
- Leave the iterator
We should not leave iterators, as this is error prone. This lead us to next solution.
Solution 2 - We use the pattern for iterator instead of while.
for(Iterator<Location> iterator2 = locationList.iterator();iterator.hasNext() && Long.MIN_VALUE != locId;) {
Location location = iterator.next();
if(locationName.equalsIgnoreCase(location.getLocationName())) {
locId = location.getLocationId(); // This will change the locId, so second condition will be no longer true and loop will end.
}
}
Pros
- It works
Cons
- It complicated, we must thing about the stop, when reading this code.
As above solution is not easy to read is should be also removed.
Solution 3 - Why break is useful.
for(Location location : locationList) {
if(locationName.equalsIgnoreCase(location.getLocationName())) {
locId = location.getLocationId();
break;
}
}
Pros
- It works
- It readable
Cons
- None
Conclusion is that the code should be readable. Using break, we point that we found the match and we do not want to progress anymore.
Fine. But what about the case when location was found ?
OP example we return 1L. This is not the best choice as is very likely that this value could be used as ID.
In previous examples i have used the min value of long. This is acceptable for some cases but, still we need to validate the method result, and also document it.
The final solution present additional loop exit, that is return key word.
public long findLocationId(String locationName) throws SystemException
{
if(locationName == null) { //Here we cover fist issue.
throw new IllegalArgumentException("THe locationName must not be null");
}
Collection<Location> locationList = getLocationList(); //The location can be read from another method so we are not binded to field.
if(locationList == null) {
throw new IllegalStateException("THe location list was not initialized");
}
for(Location location : locationList) {
if(locationName.equalsIgnoreCase(location.getLocationName())) {
return location.getLocationId(); //We exit from the method.
}
}
throw new SystemException("Could not found location for name:" + locationName);
}
Additional note
In the example OP have location == findLoc.getLocationName(), the problem with this code is that we should not use == to compare objects types (details). As we deal with String class recommended method is to use method String#equals(Object) or 'String#equalsIgnoreCase(String)'. For this example i have used the second option.
It is because there isn't always going to be a case when location == findLoc.getLocationName(). Even if that IS the case, the java compiler doesn't know what sort of input you are giving your program so it it telling you that there could be a case when the function doesn't return anything even though it MUST return a long.
Just return -1L or something that your pogram can consider to be "not found" at the end of the function.
It is because all control flows in a function should end in returning a long value.
In your case assume that there is no match in the list, so the return statement will never get executed that is why the error is reported.
To fix this you can add a return statement at the end of the function with a default value, or if your logic permits you can throw an execption saying location is not found.
Solution 1: If you want to return 1 if there is no match
public long findLocationId(String location) throws SystemException {
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,
-1);
for (Location findLoc : locationList) {
if (location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
break;
}
}
return locId;
}
Solution 2: Throw an exception if the location is not found
public long findLocationId(String location) throws SystemException {
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,
-1);
for (Location findLoc : locationList) {
if (location == findLoc.getLocationName()) {
return findLoc.getLocationId();
}
}
throw new SystemException("Unable to find the location");
}
public long findLocationId(String location) throws SystemException
{
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
}
}
return locId;
}
try this you get anwser
There must a default return statement. As there are only return statement which also is conditional, compiler will force you for default one.
public long findLocationId(String location) throws SystemException{
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
return locId;
}
}
return locId; // default return value
}
public long findLocationId(String location) throws SystemException
{
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
break;
}
}
return locId;
}
That is because your return statement in your if statement, which is conditional. Hence, if there is a case where the control never enters the if block, the method would be left without a return value.
Therefore, have a default return at the end of the method.
In case your if statement didn't find any location that is equal to your location means what will happen. That is why this compilation error happens. So you must add a return statement at end of your method.
public long findLocationId(String location) throws SystemException
{
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
**return locId;**
}
}
return
}
Your return statement is in an "if" statement, which means it will not be reached if the "if" evaluates to false. You need a return statement outside of the "if" statement.
The problem is: what would your method return if the condition in your loop is not met?
You need to return a default value, and the return statement needs to be placed after the for-loop.
You just have to add a return statement in the case the element is not found.
Trivial self-contained example:
public class Main {
public static long findStringIDX(String[] myList, String myString) {
long locId = 0;
for (String s : myList) {
if (myString.equalsIgnoreCase(s)) {
return locId;
}
locId++;
}
return -1; // Not found
}
public static void main(String[] args) {
String[] myList = new String[] { "hello", "world", "bobby" };
System.out.println(findStringIDX(myList, "bobby"));
}
}
there are 2 issues in your code.
there must be exactly one return for a method, but being in for loop, since its also a conditional flow (it may not even run a single time) you must provide an alternate return statement. though it will return whatever comes first.
there must be a return in every flow. but since your return is in if condition, there would be missing a return statement if if-expression is false. You would then require to provide an alternative return statement outside if. (else compiler will show error)
in your code:
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
return locId;
}
}
return locId; // adding this would fix the problem
Simple way to do that.
public long findLocationId(String location) throws SystemException
{
long locId = 1; // but i suggest to put -1
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
return findLoc.getLocationId();
}
}
return locId;
}
You should use break statement to come out from the loop if you do not use to execute the loop more.
You can not use the return statement inside a for loop as this return statement will call multiple times.
And the method demand only one return statement at a single time. Here break statement will will just break out of the innermost loop (here for loop).
public long findLocationId(String location) throws SystemException
{
long locId = 1;
List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
for(Location findLoc : locationList) {
if(location == findLoc.getLocationName()) {
locId = findLoc.getLocationId();
break;
}
}
return locId;
}
For more details:Please visit here

In Java, how should I declare the return type if a recursive method can return mixed values?

I have the following method definition which is intended to search a JSON object for a given key and return either the JSONObject or the String value of that key. To ensure it searches through every level of the JSON object I have made it recursive, but only in the event that a deeper JSONObject can be returned. The compiler complains that this must return an Object because I have declared that return type. Fine. In two cases I am returning an object but I think its problem is that in some circumstances it will not return anything. If I add a final return false, or something, it will pass the compiler check but a call to this method will always then (eventually) return false making it useless. I am not used to a strictly typed language like Java so I haven't encountered a similar issue before. Any pointers would be appreciated.
public Object find(String contentId, JSONObject node) {
JSONObject currentNode = (node != null) ? node : this.txtContent;
Iterator<?> nodeKeys = currentNode.keys();
while ( nodeKeys.hasNext() ){
try {
String key = (String) nodeKeys.next();
if (key.equals(contentId)) {
if (currentNode.get(key) instanceof JSONObject) {
return currentNode.getJSONObject(key);
} else {
return currentNode.getString(key);
}
} else if (currentNode.get(key) instanceof JSONObject) {
find(contentId, currentNode.getJSONObject(key));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
Let's see, you should use the value returned by the find call and return null if not found:
public Object find(String contentId, JSONObject node) {
JSONObject currentNode = (node != null) ? node : this.txtContent;
Iterator<?> nodeKeys = currentNode.keys();
while ( nodeKeys.hasNext() ){
try {
String key = (String) nodeKeys.next();
if (key.equals(contentId)) {
if (currentNode.get(key) instanceof JSONObject) {
return currentNode.getJSONObject(key);
} else {
return currentNode.getString(key);
}
} else if (currentNode.get(key) instanceof JSONObject) {
Object foundObj = find(contentId, currentNode.getJSONObject(key));
if (foundObj!=null) {
return foundObj;
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return null;
}
The Either class was made for situations just like this. See the documentation here
Usage:
Either<OneResultType,OtherResultType> result;
This avoids expensive instanceOf checks. Return null if the object is not found.
add return null; below the while loop
This method would only keep returning false if it kept hitting the else if constantly until the while loop condition ends and you get to your "return false".
Instead of return false have return null; at the very end and in the calling method have a check to see if the returned object was null which means nothing was found

check if an object is null

I have a linked list in which first node contains null object. means firstNode.data is equal to null, firstNode.nextPointer = null, firstNode.previousPointer = null.
And I want to check if firstNode is null or not.
So I tried-
if(list.firstNode == null){
//do stuff
}
but this doesn't works?
I also tried equals too. Any suggestions?
I tried printing. And I got as-
{null} -- firstNode
I think your firstNode is not null, but its fields are. Try something like this:
if (list.firstNode.data == null) {
//do stuff
}
Did you try
if (list.firstNode.data == null) { /* Do stuff */ }
You checking for list.firstNode being null. Do you mean to check for
list.firstNode.data==null
The answer is in the question. You said:
have a linked list in which first node contains null object. **means firstNode.data is equal to null**,
This means you should do the following instead:
if(list.firstNode.data == null){
//do stuff
}
It seems to me that your question is related to the processing of a doubly-linked list.
To check if empty use: (list.firstNode.next == list.firstNode.previous) this is true for an empty doubly linked list.
You can check if all the fields of the node are null:
Node firstNode = list.firstNode;
if(firstNode.data == null &&
firstNode.nextPointer == null &&
firstNode.previousPointer == null) {
//Do stuff
}
Or to prevent code repetition, you can either create an instance method isNull() to do the test or create a NULL object and override the equals method in your Node class to check if a node is equal to the null node as you described.
class Node<E> {
//The null node, assuming your constructor takes all three values.
public static final Node NULL = new Node(null, null, null);
//Fields here with constructors etc.
#Override
public void equals(Object obj) {
if(!obj instanceof Node) return false;
Node<?> node = (Node<?>)obj;
if(node.data.equals(this.data) &&
node.nextPointer == this.nextPointer &&
node.previousPointer == this.previousPointer) {
return true;
} else {
return false;
}
}
Then when you want to check if a node is null you can do:
if(list.firstNode.equals(Node.NULL)) {
//Do stuff
}

Categories