How to compare two 2D Arrays in Java? - java

I am a beginner trying to write a function in Java that returns true if two passed 2D arrays of int type are the same size in every dimension, and false otherwise. Requirements are that if both arrays are null you should return true. If one is null and the other is not you should return false.
Somehow getting an error for my code:
public static boolean arraySameSize(int[][] a, int[][] b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.length == b.length) {
for (int i = 0; i < a.length; i++) {
if (a[i].length == b[i].length) {
return true;
}
}
}
return false;
}
Any help would be appreciated!
Edit: Problem is "Runtime Error: null"

Your logic looks almost spot-on already. The only issue I see is in the logic handling the case where both arrays are not null and have the same first dimension. You should be returning false if any index does not have matching lengths:
public static boolean arraySameSize(int[][] a, int[][] b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.length != b.length) {
return false;
}
// if the code reaches this point, it means that both arrays are not
// null AND both have the same length in the first dimension
for (int i=0; i < a.length; i++) {
if (a[i] == null && b[i] == null) {
continue;
}
if (a[i] == null || b[i] == null) {
return false;
}
if (a[i].length != b[i].length) {
return false;
}
}
return true;
}
Follow the demo link below to see some of examples of this method working correctly.
Demo

Related

Return true if sub-list at given index is NOT null, false otherwise

I get AssertionError with my working out.
public boolean subListNullCheck (ArrayList<ArrayList<Integer>> list, int j) {
if(list == null || list.isEmpty() || list.get(0).isEmpty() ) {
return false;
} if(list.contains(j)) {
return true;
}
return false;
}
list.contains(j) returns true if that list contains the value j, not if the element at index j is not null.
You can write:
public boolean subListNullCheck (ArrayList<ArrayList<Integer>> list, int j) {
if (list == null) {
return false;
} else if (j >= 0 && list.size > j && list.get(j) != null) {
return true;
}
return false;
}
Or simply
public boolean subListNullCheck (ArrayList<ArrayList<Integer>> list, int j) {
return list != null && j >= 0 &&& list.size > j && list.get(j) != null;
}

Comparison method violates its general contract, sorting by different properties

Need to sort some items based on a time stamp/ current hour and/or the name property of the item's person object in alphabetical order. How would I correct the IllegalArgumentException which is thrown in some cases?
public static final Comparator<Item> sortByTimeAndName = new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
if(lhs.getDate() != null && rhs.getDate != null){
if (lhs.getDate().getTime() < rhs.getDate().getTime()) {
return -1;
} else if (lhs.getDate().getTime() == rhs.getDate().getTime()) {
if (lhs.getHour() < rhs.getHour()) {
return -1;
} else if (lhs.getHour() == rhs.getHour()) {
if(lhs.getPerson().getName().compareTo(rhs.getPerson().getName()) == 0){
// if two persons have same name, sort by person id
if (lhs.getPerson().getID() < rhs.getPerson().getID()){
return -1;
}
}
else{
return lhs.getPatient().getName().compareTo(rhs.getPatient().getName());
}
}
}
}else{
if (lhs.getHour() < rhs.getHour()) {
return -1;
} else if (lhs.getHour() == rhs.getHour()) {
if(lhs.getPerson().getName().compareTo(rhs.getPerson().getName()) == 0){
if (lhs.getPerson().getID() < rhs.getPerson().getID()){
return -1;
}
}
else{
return lhs.getPerson().getName().compareTo(rhs.getPerson().getName());
}
}
}
return 1;
}
};
Stack trace:
Caused by java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:761)
at java.util.TimSort.mergeAt(TimSort.java:497)
at java.util.TimSort.mergeCollapse(TimSort.java:421)
at java.util.TimSort.sort(TimSort.java:210)
at java.util.Arrays.sort(Arrays.java:1998)
at java.util.Collections.sort(Collections.java:1900)
....
Assume there are 3 objects of type Item such as:
for a: assume getDate() == null
for b: assume getDate() != null
So the comperartor's result is
assume if (lhs.getHour() < rhs.getHour()) is true then a < b
also
for b: assume getDate() != null
for c: assume getDate() != null
So the comperartor's result is
assume if (lhs.getDate().getTime() < rhs.getDate().getTime()) is true then b < c
also
for a: assume getDate() == null
for c: assume getDate() != null
So the comperartor's result is
assume if (lhs.getHour() > rhs.getHour()) is true then a > c (because of the final return 1)
As you can see there is a contradiction:
a < b and b < c but a > c
I believe that cases like this violate the comparison method's general contract.

How to simplify logic checking if all cells in a record of array are null using for

Can this code to be simplifed using for?
if ((col[0] == null) && (col[1] == null) && (col[2] == null) && (col[3] == null) && (col[4] == null)){
//statement
}
You can use a Java 8 feature with Stream API:
boolean allNull = Arrays.stream(col).allMatch(Objects::isNull);
Use a boolean flag:
boolean areAllNull = true;
for (int i = 0; i < col.length; i ++) {
if (col[i] != null) {
areAllNull = false;
break;
}
}
if (areAllNull) {
//statement
}
If you want to limit only to certain positions in the array change col.length by a variable or constant marking the limit:
int numberOfPositions = 5;
for (int i = 0; i < numberOfPositions ; i ++)`
To check if X elements in an array are null, you cannot reduce the number of checks (X) unless you can short-circuit them. However, you can have a cleaner "if" statement if you package it in a method:
if (isAllNull(col, 0, 4)){
// do stuff
}
public boolean isAllNull(Object[] col, int start, int end){
for (int index=start;index<=end;index++){
if (col[index] !=null){
return false;
}
}
return true;
}
This will return false immediately when it finds one of the values not null.

Method always returns true?

I have a method that is being called to validate that an IP address is assignable. No matter what I pass to it, it is always returning true. What do I need to set the return as to get this method working properly?
public boolean checkValidIPClass(String x) {
for (int i = 0; i < 4; i++) {
try {
if (retString.equals("A")) {
if ((intParts[1] == 0) && (intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[1] == 255) && (intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("B")) {
if ((intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("C")) {
if (intParts[3] == 0)
return false;
if (intParts[3] == 255)
return false;
}
} //ends try
catch (NumberFormatException nfe) {
return false;
} //ends catch
} //ends for
return true;
}
retString is making it to the method and is a string that was returned from another method that checks what class the IP address is and assigns it, this was verified with a print statement. Thanks!
EDIT: How has this been answered and downvoted? My question wasn't about comparing the strings, it was about the method always returning true even when I know the if statements should be catching the error and returning false?
EDIT2: Updated my code.
I don't get why you're doing a loop, but you could try this:
public boolean checkValidIPClass(String ipClass, String ipAddress)
{
if (ipClass.contentEquals("A"))
{
if (ipAddress.endsWith("0.0.0") || ipAddress.endsWith("255.255.255"))
return false;
}
else if (ipClass.contentEquals("B"))
{
if (ipAddress.endsWith("0.0") || ipAddress.endsWith("255.255"))
return false;
}
else if (ipClass.contentEquals("C"))
{
if (ipAddress.endsWith("0") || ipAddress.endsWith("255"))
return false;
}
return true;
}
Since you're just checking the ending array parts of the IP address, you don't need to break it into an array, just leave it as a string.
And keep in mind that this would only satisfy IPv4 formatted IP addresses. It will not work for IPv6 formatted addresses

this method must return a result of type boolean, java

public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
}
It returns me this error: this method must return a result of type boolean. What am I doing wrong?
Right now, the function isn't guaranteed to return a boolean, because it's possible that neither of the if statements will ever be entered.
You could fix it like this (but only do this if it's actually what your logic needs!):
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
return false;
}
The Java compiler doesn't make assumptions that a for loop will have an iteration or that an if statement block will run.
There are execution paths where there is no return statement. What happens if the execution path doesn't execute any of the existing return statements and drops to the bottom? There isn't a return there.
Add a return at the bottom.
All possible ways that the method can exit need to return something. If your code makes it through both for loops without having an if condition evaluate to true, then you need a return at the end that specifies what gets returned.
The compiler is not aware that at least one of the loops will be executed. It takes into account all the possibilities of the execution and one of them is that neither of the loops will be executed and in that case there is no return statement. So insert a return statement out of the loops as well.
The answer to this question is easy. It happened to me too. The problem in your code is that you don't say to the computer what to do in case that the "if" statement is wrong, so you just have to add an "else {return false}" to every "if". Another tip is: please make your code cleaner and readable.
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]) {
return true;
} else {
return false;
}
}
for (int i=0; i<7; i+=3) {
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;
} else {
return false;
}
}
}

Categories

Resources