Comparing two integer arrays in Java
public static void compareArrays(int[] array1, int[] array2) {
boolean b = true;
if (array1 != null && array2 != null){
if (array1.length != array2.length)
b = false;
else
for (int i = 0; i < array2.length; i++) {
if (array2[i] != array1[i]) {
b = false;
}
}
}else{
b = false;
}
System.out.println(b);
}
How to compare int arrays in Java?
A few things to note here:
==
compares the references, not the values . . . that is, you are asking whether these two arrays are the same exact instance, not whether they contain the same values.- The fact that you are using
==
means you may not know about theequals()
method onObject
. This is not the method you'll need to solve this current problem, but just be aware that in general, when you compare the values of two objects, you should be usingobj1.equals(obj2)
, notobj1 == obj2
. Now==
does work with primitives likeint
(e.g. plain oldx == 3
and so on), so maybe that's why you were using it, but I just wanted to make sure you were aware ofequals()
vs.==
. - In the old old days (pre-1998), you would have to compare each element pair of the two arrays. Nowadays, you can just use that static
Arrays.equals()
method on thejava.util.Arrays
class. This method is overloaded for all the primitive types (using==
under the hood for each element pair) and forObject
(where it will most definitely useequals()
for each pair.)
Compare two array and return an array to show which elements are equal or not
In the second loop when comparing both matrices if they are equal you must set the flag to true and break the second loop, so the first loop will compare the next element, for example:
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 3};
HashMap<Integer, Boolean> map = new HashMap<>();
for (int i : arr1) {
for (int j : arr2) {
if (j == i) {
map.put(i, true);
break;
} else {
map.put(i, false);
}
}
}
System.out.println(Arrays.asList(map));
Output:
[{1=true, 2=false, 3=true, 4=false, 5=false}]
How to compare two-dimensional (or nested) Java Arrays?
You are comparing two dimensional arrays, which means the elements of these arrays are themselves arrays. Therefore, when the elements are compared (using Object
's equals
), false
is returned, since Object
's equals
compares Object
references.
Use Arrays.deepEquals
instead.
From the Javadoc:
boolean java.util.Arrays.deepEquals(Object[] a1, Object[] a2)
Returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object [], Object []) method, this method is appropriate for use with nested arrays of arbitrary depth.
Java Comparing Two Arrays for Login
You might want to use a map for this.
- the map will return
null
if the user doesn't exist so the check will fail. - or it will return the password for the user and the password check will fail.
- Returns are immediate after the result message is displayed.
static Map<String, String> users = new HashMap<>();
String[] username = { "admin", "john", "alina" };
String[] password = { "123", "456", "789" };
// build the map.
for (int i = 0; i < username.length; i++) {
users.put(username[i], password[i]);
}
userLogin();
public static boolean userLogin() {
Scanner input = new Scanner(System.in);
System.out.println("Enter your username: ");
String user = input.nextLine();
System.out.println("Enter your password: ");
String pass = input.nextLine();
String password = users.get(user);
if (pass.equals(password)) {
System.out.println("Login Success! Loading the menu...");
return true;
}
System.out.println(
"Invalid username or password, please contact your Database Administrator for "
+ "support!");
return false;
}
comparing arrays in java
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
How to compare arrays without using .equals and with a false boolean
Instead of immediately returning when they are equal, check for inequalities and if there's one, then return false
. If the for
loop finishes without returning, then you can safely return true
.
if (arrayOne.length == arrayTwo.length) {
for (int i = 0; i < arrayOne.length; i ++) {
if (arrayOne [ i ] != arrayTwo [ i ] ) {
return false;
}
}
return true;
}
return false;
Comparing elements of arrays in java
So you want to //Do Something
if the ParkedCar's 5th value is higher than the minutes purchased.
You can write a function to do this.
Including checks for if both arrays are same size.
Your function is simply
for(int i = 0, i < parkingLot.getLength(), i++) {
if(parkingLot[i].getFifthValue() > meters[i].getMinutesPurchased()))
//DoSomething
}
However, ParkedMeter is quite a simple class. Why not add that as an attribute to ParkedCar. In that case, this meter value check is simply a oneliner boolean function in your ParkedCar Class return fifthValue > minutesPurchased;
Comparing two arrays of String and returning comparison in Java
using the stream API, you could do:
String[] result = Arrays.stream(a1)
.filter(new HashSet<>(Arrays.asList(a2))::contains)
.toArray(String[]::new);
Edit:
just for those curious about whether a new set will be constructed for each element, this is not the case at all.
only one Set instance is constructed, the above code is equivalent to:
List<String> list = new ArrayList<>();
HashSet<String> strings = new HashSet<>(Arrays.asList(a2));
for (String s : a1) {
if (strings.contains(s)) list.add(s);
}
String[] result = list.toArray(new String[0]);
Related Topics
How to Pass a Value from One Jsp to Another Jsp Page
Netbeans How to Set Command Line Arguments in Java
How to Attach Source or Javadoc in Eclipse for Any Jar File E.G. Javafx
Why Does Java Allow Arrays of Size 0
What Does "An Arbitrary Object of a Particular Type" Mean in Java 8
Eclipse Error ... Cannot Be Resolved to a Type
When Using Mokito, Differencebetween the Actual Object and the Mocked Object
How to Get All Methods of a Class
Maximum Size of a Method in Java
Why Functional Interfaces in Java 8 Have One Abstract Method
Zoom Box for Area Around Mouse Location on Screen
Java: CSV File Easy Read/Write
How to Load Image File to Imageview