how do i make arrays equal if they have to be filled? - java

i am confused because I need my array to be equal to the other array but I don't know how to compare them without losing their values

If both roots are null you will get an undesired result based on what you're trying to do with your second if condition.
It looks like if both roots are null you want to return true, but you're returning false. You could use just one if statement
if(thisRoot == null || otherRoot == null){
return thisRoot == null && otherRoot == null;
}
You have a bigger problem with how you're comparing the data of the two nodes.
thisRoot.getData() != otherRoot.getData()
This comparison is not what I think you're looking for. Instead you should overrride the equals method for your data objects and compare using it instead

The order of your conditions causes a problem.
if (thisRoot == null || otherRoot == null) {
return false;
}
if (thisRoot == null && otherRoot == null) {
return true;
}
The first condition will evaluate to true (and lead to return false) even if both branches are null.
You should first evaluate if both branches are null; after that, you can check the case where only one of them is null.

Related

Check if two objects are not equal, unless they are both null

The following Java snippet of code confuses me a bit. The method is trying to check whether two objects are NOT equal, using the standard .equals() method to denote that they are equal. Additionally, a boolean can determine whether two null's are considered equal or not. I'm wondering if:
The boolean logic in this method is indeed correct?
the return statement in the middle block can be omitted somehow. Could this logic be rewritten in a more concise or other way, maybe dropping the empty return, but keeping a high level of human readability of the code?
Snippet:
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual)
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable == null || otherVariable == null)
{
return;
}
if(variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Yes, the logic in the method is correct. It throws the exception if the two objects are equal. You could remove the second condition and combine it with the third one, but I don't see much point. If you did, the method might look like this.
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual) throws Exception
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable != null && variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Note that there's no need to check whether otherVariable is null separately, since the equals method on variable should return false if otherVariable is null.
There's an even more concise way to write this, but it's not worth considering, since it sacrifices readability.

Java Multiple comparision in java

Pardon me if this is a stupid question.. I was wondering if there is any support for following comparison in Java:
(a, b, c .... != null) in place for :
(a != null && b != null && c != null && d ! null and so on ..)
I was trying to make code more readable as my code which is almost unreadable due to multiple condition in single statement.
code :
variable = (rest.host != null && rest.payload != null
&& rest.lockQueue != null && rest.endpoint != null ) || rest.default.setState
|| rest.scheduler.locked && rest.scheduler.queue.isFull()
&& lastPayload.getActivity.status.executing ? onExecute(rest.payload) : wait(TIME);
If your elements are in a collection, use collection.stream().allMatch(x -> x != null). Actually, there's even a predicate for that: collection.stream().allMatch(Objects::nonNull).
If your elements aren't in a collection, you can still use Arrays.asList() to create an ad-hoc list from them. So, in your case:
Arrays.asList(rest.host, rest.payload, rest.lockQueue, rest.endpoint).stream().allMatch(Objects::nonNull)
EDIT: actually, as someone mentioned in another answer, there is a method that creates a stream directly, namely Stream.of(...). So:
Stream.of(rest.host, rest.payload, rest.lockQueue, rest.endpoint).allMatch(Objects::nonNull)
You could do something like this to make sure everything is not null, if using a Java version lower than 8. Otherwise I would go with the other people's answers using streams.
private boolean checkIfNotNull( Object ... objects ) {
for(int i = 0; i < objects.length; i++) {
if(objects[i] == null)
return false;
}
return true;
}
and you could pass in all the objects that you want to check if they are null.
then you can call this in the if statement such as
if( checkIfNotNull( a, b, c, d, e, f, g ) ) {
//do stuff
}
In java 8, it could be done as next Stream.of(a, b, c, d).allMatch(Objects::nonNull), it will return true if they are all non null.
I think if you want your code more readable, you should replace your comparisons with method calls that "says" what each comparison is.
Example:
if (isAllRight(a, b, c)) {
...
}
In other cases you can break them into single comparisons and check one by one:
if (a == NUL) {
return false;
}
if (b == NULL) {
return false;
}
return true;

Confuse "==null" and "==" "" in java?

I have a simple issue related ==null and =="" ,i think everybody know this issue .
Here's an example:
#SuppressWarnings("unchecked")
public void reorderingCriteia() {
ListModelList<ReorderData> headerList = new ListModelList<ReorderData>();
List<String> headerId = new ArrayList<String>();
String userReorderSelection = Services.userPreferenceService().getUserPreference().getUserOption("PROCESS_CHECKLIST_COLUMN_REORDER");
if (userReorderSelection == null || userReorderSelection == "") {
int i = 0;
for (ReorderData rd : availableReorderList) {
headerList.add(rd);
headerId.add("" + i);
i++;
}
folderProcessModel.setHeaderList(headerList);
folderProcessModel.setHeaderId(headerId);
} else {
headerList = ReorderDialogViewModelNew.jsonStringToList("FOLDER_PERMIT_LIST_COLUMN_REORDER", userReorderSelection, false);
headerId = compHelper.intializeSequnce(headerList, folderProcessModel.getAvailableHeaders());
folderProcessModel.setHeaderList(headerList);
folderProcessModel.setHeaderId(headerId);
}
}
I have some questions:
Here this code use if (userReorderSelection == null || userReorderSelection == ""). Can i use this condition if (userReorderSelection == null) ?
What is the difference between two ?
== null checks for null reference.
== "" check for blank/empty string reference. Here you could use str.equals("") to check if the string is empty/blank or not. == is used for object reference checks. Or you can use the String.isEmpty() to check the same.
Also, if you use just if (userReorderSelection == null), then you'll only be checking if the userReorderSelection is null or not and it won't determine whether the String is empty or not.
As everyone replied:
"" checks for empty String.
null checks for null reference.
Use StringUtils from apache commons to eliminate two conditions. StringUtils.isEmpty(yourVariable) this condition will handle both cases.
"" --> indicates empty String in Java. Rather than using userReorderSelection == "" it is preferable to us
userReorderSelection.isEmpty() // But make sure that userReorderSelection is not null
null --> indicates Null references (can be reference of any object)
If you do not have this check it may result in NullPointerException if you try to use this reference. Empty String will not throw such exceptions.
== null checks to see if the object reference is null.
== "" checks to see if the object reference equals a blank string
str.equals ("") checks to see if your String object contains the empty string.
I guess what you want is
if (userReorderSelection == null || userReorderSelection.equals (""))

What is the correct way to implement compareObjects()

I have compareObjects method implemented as below
public static int compareObjects(Comparable a, Comparable b){
if (a == null && b == null){
return 0;
} else if (a == null && b != null){
return -1;
} else if (a != null && b == null){
return 1;
} else {
return a.compareTo(b);
}
}
When I run this through findBugs, I get this suggestion on the line return a.compareTo(b):
There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs. Due to the fact that this value had been previously tested for nullness, this is a definite possibility.
At this point a can never be null. Why does FindBugs show me this suggestion? How can I correct this; what is the correct way to implement compareObjects()?
I think it might be because you don't need the extra && statements. After the first if statement you already know that one of them is null.
public static int compareObjects(Comparable a, Comparable b){
if (a == null && b == null){
return 0;
} else if (a == null){
return -1;
} else if (b == null){
return 1;
} else {
return a.compareTo(b);
}
}
Looking at it again , try this code:
if (a == null && b == null){
return 0;
}
if (a == null){
return -1;
}
if (b == null){
return 1;
}
return a.compareTo(b);
It may be a limitation in FindBugs; I agree that you've covered all the bases, but your null-check is split across two different conditions. Now these conditions happen to be complementary, so at least one of them will fire if a is null, but depending how sophisticated FindBugs is, it may not recognise this.
Two options here, then:
Just ignore the FindBugs warning. Due to its nature it will raise some false positives from time to time, so don't feel like you have to rewrite your code to make it 100% happy if you don't think the rewrite is worthwhile on its own merits.
You can use the #SuppressWarnings annotation to actually communicate this to FindBugs, if you want the report to show a nice big zero at the end. See this question for an example.
Restructure the condition so that the nullity check on a is more explicit, by nesting if blocks:
if (a == null) {
return b == null ? 0 : -1;
}
return b == null ? 1 : a.compareTo(b);
Depending on your tastes and style that might be a better rewrite anyway, in that is more clearly says "if a is null, do this calculation and return it, otherwise do this calculation". You can of course change the ternary condition into another if-else block if you prefer that.

How to compare value in array?

how to compare value in an array?
I have array named list which contains 12 elements. I see if value in index 0 is equal or not equal to value in index 2.
I have tried this code but it doesnt seems to work.
if ((list.get(0)==list.get(2) && list.get(1)==list.get(3))
{
System.out.println("equal")
}
If it's really an array, you want:
if (list[0] == list[2] && list[1] == list[3])
Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want:
if (list[0].equals(list[2])) && list[1].equals(list[3]))
Although that will then go bang if any of the values is null. You might want a helper method to cope with this:
public static objectsEqual(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
return o1.equals(o2);
}
Then:
if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3]))
If you've really got an ArrayList instead of an array then all of the above still holds, just using list.get(x) instead of list[x] in each place.
if(list[0] == list[2] && list[1] == list[3]){
System.out.println("equal");
}
If they are strings:
if(list[0].equals(list[2]) && list[1].equals(list[3])){
System.out.println("equal");
}
You are comparing object references, not objects themselves. You need to use a method call. All classes inherit equals() from the root Object class, so it might work:
if(list.get(0).equals(list.get(2)) && list.get(1).equals(list.get(3)))
{
System.out.println("equal");
}
This article seems to be a good summary of other comparison methods available.

Categories

Resources