Check return value for if-statement - java

I'm trying to make a bit of code that returns a boolean value depending on whether an item was successfully removed from a HashMap or not.
My understanding is that map.remove(Key) should return the Key if it worked and null if not. My approach was to check if the return value is null and print false if it is, true if anything else.
The problem I'm having comes from that I don't know how to check what the return value was inside my method.
Here is my attempt so far.
public boolean deleteMapEntry(String entry)
{
testMap.remove(entry);
if(null)
{
return false;
}
else
{
return true;
}
}
Obviously saying if (null) doesn't work, but I can't find what would.

You need to assign the value of testMap.remove(entry) to a variable to test it to see if it is null...
String value = testMap.remove(entry);
return value != null;
you can also just test what you remove directly and not use a variable:
return testMap.remove(entry) != null;

Related

How can I junit test the last block of this equal?

How can I JUnit test the last block of this equal?
Any help would be much appreciated. This is the method in question:
#Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
//unreachable block
ServiceOrderRelationship serviceOrderRelationship = (ServiceOrderRelationship) o;
return Objects.equals(this.id, serviceOrderRelationship.id) &&
Objects.equals(this.href, serviceOrderRelationship.href) &&
Objects.equals(this.relationshipType, serviceOrderRelationship.relationshipType) &&
Objects.equals(this.baseType, serviceOrderRelationship.baseType) &&
Objects.equals(this.schemaLocation, serviceOrderRelationship.schemaLocation) &&
Objects.equals(this.type, serviceOrderRelationship.type) &&
Objects.equals(this.referredType, serviceOrderRelationship.referredType);
}
This is what I've been doing but I can never reach the last block of code inside the equals method:
#Test
public void testEquals() throws Exception {
assertFalse(serviceOrderRelationship.equals(null));
assertTrue(serviceOrderRelationship.equals(serviceOrderRelationship));
assertFalse(serviceOrderRelationship.equals(serviceOrderRelationship1));
}
First of all, thank you all for your responses!
This is how I was able to reach the last block of the equals method. I had to initialize both objects di and di1 and set every variable to the same value, then test the equals condition switching back and forth one variable at a time to a different value. This is an example from another POJO:
// Initialize objects
di.setEdgeId("edgeId");
di.setIdentityEndpoint("identityEndpoint");
di.setUsername("username");
di1.setEdgeId("edgeId");
di1.setIdentityEndpoint("identityEndpoint");
di1.setUsername("username");
// Change value of var and test equal
di1.setEdgeId("edgeIdm");
assertFalse(di.equals(di1));
di1.setEdgeId("edgeId");
// same
di1.setIdentityEndpoint("identityEndpointm");
assertFalse(di.equals(di1));
di1.setIdentityEndpoint("identityEndpoint");
// Same
di1.setUsername("usernamem");
assertFalse(di.equals(di1));
di1.setUsername("username");
// Then at the end perform the other tests
assertTrue(di.equals(di));
assertTrue(di.equals(di1));
assertFalse(di.equals(null));
assertFalse(di.equals(42));
Your problem might be that one of the follow cases, in which the method would return prematurely.
If serviceOrderRelationship and serviceOrderRelationship1 are references to the same object, the true would be returned. Similarly, if they are not of the same type, false would be returned. If serviceOrderRelationship1 is null, false would be returned.
If serviceOrderRelationship is null, then calling equals on it would throw a NullPointerException.

Get the only element in a Set

I need to know the "best" and safest way to get a value held within a Set if there is only one entry. methodToGetValues() is used extensively to read config files and return a list of values given a specific key, in this case "enabled". For the enabled key, there should only be one entry returned in the Set, obviously "true" or "false" but, mistakes happen. I have the following which seems a little convoluted:
Set<String> enabled = methodToGetValues("enabled");
if (!enabled.isEmpty() && enabled.size() < 2 && "true".equals(enabled.iterator().next())) {
...
}
Can anyone suggest a simpler yet still robust way of checking this?
Your question asks to get something from the Set. But your example just needs a check.
If you know what to expect in the Set, this works fine.
if (enabled != null && enabled.size() == 1 && enabled.contains("true")) {
...
}
Otherwise, if you just want to get the element but don't know what it is, the iterator you suggested works fine.
String getOnlyElement(Set<String> enabled, String default) {
return (enabled == null || enabled.size() != 1) ? default : enabled.iterator().next();
}
I like having null checks but it depends on what methodToGetValues returns.
Unsure of what the use case is that would drive using a Set<String> for this data but here is an option:
// check size = 1 over two checks, use contains rather than grabbing an iterator
if (set.size() == 1 && set.contains("true")) {
...
}
public Set<String> getValues(final String key){
.....
}
public String getValue(final String key) {
final Set<String> values = getValues(key);
if (values == null || values.size() != 1) {
throw new IllegalStateException("Invalid configuration for give key :" + key);
}
return values.iterator().next();
}
public Boolean getValueAsBoolean(final String key) {
return Boolean.valueOf(getValue(key));
}
You can modify method to have accept argument to return default value when keys are not found. You can add different methods to return specific type object like inte, boolean, this way code looks cleaner

Missing a return statement somewhere?

I'm working on a basic Java assignment for school. This snippet involves searching for a specific part number in an ArrayList. When I try to compile, the IDE says I have a missing return statement. However, I can't see where it is. Do I need a return statement following the increment of the index? If so, then the return null becomes unreachable. Thank you guys very much.
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
boolean searching = true;
while (index < items.size() && searching){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == (searchPartNumber)){
searching = false;
return inventoryItem;
}
else{
index++;
}
if(searching){
return null;
}
}
}
your code has several problems:
after you compared first item in list and it does not match - you will stop comparing, as searching is true and you will return null
in case of empty list you need to return null too
here is the fixed version:
public InventoryItem findInventoryItem(int searchPartNumber) {
for (InventoryItem inventoryItem : items)
if (inventoryItem.getPartNumber() == searchPartNumber)
return inventoryItem;
return null;
}
The method expected a return value in all cases. This means you have to add a return value in the else-block, too. Or you could add a return value only once at the end of all statements.
you're not handling the case where search will not be true.
That is,
if(searching){
return null;
}
Where is the else part handled here?
No matter what happens in your method, there has to be some value returned (even if it is null).
Right now, if you never get into your while (because that condition isn't fulfilled to begin with -> like when items.size() is 0), your method won't return anything.
In other words: Put a return null; after the closing bracket of your while loop.
Another important note: You do realize that this while will always only look at the first item, right? Because if your first item is not the one you're searching for, your variable searching will still be true, which will then force the method to return null (without looking at any other items)
You are missing a return statement right at the end, after the while loop.
This is needed to handle the case where the while loop guard becomes false, either by items being empty, or searching being set to false.
The compiler has no way of determining whether these will never become false, so you it requires you to return in case they do.
All functions that have a type (aren't void) require that you return something based on the method signature. This means that you must return something in ALL cases. You haven't included the case where searching is not true, and must return something if that is the case.
if(searching){
return null;
} else{
//return something else
}
It is important to note though that in this case the else is implicit, and therefore you don't actually have to provide the else. You could instead just do this:
if(searching){
return null;
}
//return something else
Keep in mind that if searching is true, it will return null and "return something else" will never be called.
Do like this
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
//boolean searching = true; comment out this line
InventoryItem inventoryItem = null; //declare null InventoryItem here
while (index < items.size())
{
inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if (fetchedPartNumber == (searchPartNumber))
{
//searching = false; comment out this line
break; //do something to get out from while loop
}
else {
inventoryItem = null;
index++;
}
}
return inventoryItem; //if found then it will have item otherwise null
}
First you need to return if items.size equals zero. Second you need to return if you find nothing. Third I can't see any usefulness of the variable searching.
You could change your searching function a bit. The final form would be something like this:
public InventoryItem findInventoryItem(int searchPartNumber) {
int index = 0;
while (index < items.size()){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == searchPartNumber)
return inventoryItem;
else
index++;
}
return null;
}

Method should check array against itself?

I tried to make a method to tell me if my array contained any duplicate coordinates, and if so set a boolean to true, else, set it to false. Any idea why it continuously returns false?
public void check(){
if(point[particle].equals(point) == true){
check = true;
} else {
check = false;
}
}
point = Point array
particle = Current particle
check = My boolean used to check
Look at this part of the code (from the condition of your if-statement):
point[particle].equals(point)
I think there is some variable shadowing (or something of that sort) going on here. point seems to be an array but you are testing for equality between a member of this array and the array itself -- this is why you keep getting false. Check your variable names and see if you accidentally used the same name for two different variables.
As a note,
if (condition == true) {
check = true;
} else {
check = false;
}
can be simplified to
check = condition;

Logical mistake or not?

I have written this function which will set
val=max or min (if val comes null)
or val=val (val comes as an Integer or "max" or "min")
while calling i am probably sending checkValue(val,"min") or checkValue(val,"max")
public String checkValue(String val,String valType)
{
System.out.println("outside if val="+val);
if(!val.equals("min") && !val.equals("max"))
{
System.out.println("Inside if val="+val);
try{
System.out.println("*Inside try val="+val);
Integer.parseInt(val);
}
catch(NumberFormatException nFE)
{
System.out.println("***In catch val="+val);
val=valType;
}
return val;
}
else
{
return val;
}
}
But the problem is if val comes null then
outside if******val=null
is shown.
Can any1 tell me is this a logical mistake?
And why will I correct?
If val is null, then the expression val.equals("min") will throw an exception.
You could correct this by using:
if (!"min".equals(val) && !"max".equals(val))
to let it go inside the if block... but I would personally handle it at the start of the method:
if (val == null) {
// Do whatever you want
}
Btw, for the sake of readability you might want to consider allowing a little more whitespace in your code... at the moment it's very dense, which makes it harder to read.
...the problem is if val comes null then outside if****val=null is shown. Can any1 tell me is this a logical mistake?
The output is correct; whether you want it to come out that way is up to you.
Your next line
if(!val.equals("min") && !val.equals("max")){
...will throw a NullPointerException because you're trying to dereference val, which is null. You'll want to add an explicit check for whether val is null:
if (val == null) {
// Do what you want to do when val == null
}
you should use valType instead of val to check either minimum or maximum is necessary to check.
My advice to you in such cases to use boolean value or enum instead of strings. Consider something like that:
/**
* check the value for minimum if min is true and for maximum otherwise
*/
public String checkValue(String val, boolean min){
if (min) {
// ...
} else {
// ...
}
}
If you need to compare strings against constants you should write it the other way around to make it null-safe:
if (! "min".equals(val))
And while this is mostly a style issue, I would make all method arguments final and not re-assign them (because that is confusing), and you can also return from within the method, not just at the end. Or if you want to return at the end, do it at the very end, not have the same return statement in both the if and the else branch.

Categories

Resources