are arrays equal method in java - java

im a newbie, i need to write a method that check if 2 arrays are equal in the values and order, if they are print true, else false
this is what i wrote and the result always true, if i try printing the values that the function recieve in the arrays for some reason they are all 0.
public static boolean areArraysEqual(int[] firstArr, int[] secArr) {
firstArr = new int[N];
secArr = new int[N];
System.out.println(firstArr.length);
if(firstArr.length != secArr.length){
return false;
}
if(firstArr == null || secArr == null){
return false;
}
for(int i = 0; i < firstArr.length; i++) {
if(firstArr[i] != secArr[i]) {
return false;
}
}
return true;
}

When you try to re-allocate the arguments firstArr and secArr, the original array contents get lost.
No need to re-allocte firstArr and secArr, since in java, array objects are passed by value, they can be used as-is for its contents.
The following code snippet is good enough:
public static boolean areArraysEqual(int[] firstArr, int[] secArr) {
if(firstArr == null || secArr == null || firstArr.length != secArr.length){
return false;
}
for(int i = 0; i < firstArr.length; i++) {
if(firstArr[i] != secArr[i]) {
return false;
}
}
return true;
}

You are creating two new arrays, which are initialized to all zeros with
firstArr = new int[N];
secArr = new int[N];
When you call areArraysEqual(int[] firstArr, int[] secArr) you are supplying two arrays already, there is no reason to create new ones.
Removing those two lines should get you going.

The issue with your code is that you are re-declaring the array. Remove firstArr = new int[N]; and secArr = new int[N]; from your code. Then it should work fine.
public static boolean areArraysEqual(int[] firstArr, int[] secArr) {
System.out.println(firstArr.length);
if(firstArr.length != secArr.length){
return false;
}
if(firstArr == null || secArr == null){
return false;
}
for(int i = 0; i < firstArr.length; i++) {
if(firstArr[i] != secArr[i]) {
return false;
}
}
return true;
}
Side note: If this is not for academic/competitive purpose use Array.equals(firstArr, secArr)

Nothing the already submitted answers don't cover, but you've got far too much code written for this. Try this:
public boolean compareArrays(int[] arr1, int[] arr2) {
if (Arrays.equals(arr1, arr2)) {
return true;
}
return false;
}
Arrays.equals covers order and size, no need to check for nulls either, that should be handled by the caller, after all, null does equal null and there for the arrays are equal.

Related

Remove first item from Array in Javax

Got an assignment question which asks to return the first item from an array and then remove it. If the array is empty I should return null. Here is my code:
public String pop(){
if(arrayLength == 0){
return null;
}else{
String[] temp = new String[100];
String firstItem = StringStack[0];
for(int i = 1; i<StringStack.length; i++){
temp[i] = StringStack[i];
}
StringStack = temp;
return firstItem;
}
}
The arrayLength variable is set by this method and works fine:
public int getLength(){
int count = 0;
for (String s : StringStack) {
if (s != null) {
count++;
}
}
return count;
}
I cant figure out what it is I am doing wrong here. Another part of this question is I cant use any collections or Systems.arraycopy so I have to use for loops and other basic operators to solve this. It also has to be an array so I cant use array lists or other data structures.
here is version with two fixed problems:
public String pop() {
if(StringStack == null || StringStack.length == 0)
return null;
String firstItem = StringStack[0];
String[] temp = new String[StringStack.length-1]; // allocate proper size
for(int i = 1; i<StringStack.length; i++){
temp[i-1] = StringStack[i]; // i-1 for temp array
}
StringStack = temp;
return firstItem;
}

How to check if the whole Array of a class is empty? [duplicate]

I have an int array which has no elements and I'm trying to check whether it's empty.
For example, why is the condition of the if-statement in the code below never true?
int[] k = new int[3];
if (k == null) {
System.out.println(k.length);
}
There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Method to check array for null or empty also is present on org.apache.commons.lang:
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.isEmpty(array);
Look at its length:
int[] i = ...;
if (i.length == 0) { } // no elements in the array
Though it's safer to check for null at the same time:
if (i == null || i.length == 0) { }
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null, when you don't new it up.
e.g.
int[] numbers = null; // changed as per #Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.
The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.
I tested as below. Hope it helps.
Integer[] integers1 = new Integer[10];
System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
for (Integer integer : integers1) {
System.out.println(integer); //prints all 0s
}
//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
// integers1[2] = 0;
for (Integer integer : integers1) {
System.out.println(integer); //Still it prints all 0s but it is not empty
//but that manually added 0 is different
}
//Even we manually add 0, still we need to treat it as null. This is semantic logic.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,
public static boolean isEmpty(#Nullable Object[] array) {
return (array == null || array.length == 0);
}
An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty.
Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.
int[] k = new int[3];
if(k.length == 0)
{
//do something
}

equals methods when using arrays java

For my equals method that checks to see if two arrays are equal, does the first method "equals" actually check if the two arrays are equal or only tests the memory addresses? Or should I include both?
public boolean equals(Object otherObject)
{
if (otherObject == null)
{
return false;
}
else if (getClass() != otherObject.getClass())
{
return false;
}
else
{
RegressionModel otherRegressionModel = (RegressionModel)otherObject;
return (xValues == (otherRegressionModel.xValues) && yValues == (otherRegressionModel.yValues));
}
}
OR
public static boolean equalArrays(double[] x, double[] y)
{
if(x.length != y.length)
{
return false;
}
else
{
for(int index = 0; index < x.length; index++)
{
if (x[index] != y[index])
{
return false;
}
}
return true;
}
}
the =/!= operator compares arrays based upon their reference, and not their content. Clearly two arrays may have the same elements, except they are still two distinct objects that are created in the memory. The arrays are two references. Therefore your second method should be applied, because it compares the actual elements inside the two arrays. Also you don't need your else statement.
public static boolean equalArrays(double[] x, double[] y)
{
if(x.length != y.length)
{
return false;
}
for (int index = 0; index < x.length; index++)
{
if (x[index] != y[index])
{
return false;
}
}
return true;
}
One more check can also be applied on first equals method where it can see both array has an same reference or not. Then other comparison can be done. In second method it always check the element of an array, even if both an reference of same array. so in terms of performance it will take time.
public boolean equals(Object otherObject)
{
if (otherObject == null)
{
return false;
}
else if (getClass() != otherObject.getClass())
{
return false;
} else if (this != otherObject)
return false;
}
else
{
RegressionModel otherRegressionModel = (RegressionModel)otherObject;
return (xValues == (otherRegressionModel.xValues) && yValues == (otherRegressionModel.yValues));
}
}
Adding to #Henry's answer, before comparing lengths of the two given arrays you should make sure that neither of them are null so that you don't get a NullPointerException.
You might also want to compare the references of the arrays before looping through their elements.
Something like this:
public static boolean equalArrays(double[] x, double[] y)
{
if (x == null || y == null || x.length != y.length)
{
//NOTE: That if both x and y are null we return false despite the fact that you could argue that they are equal
return false;
}
if (x == y)
{
return true;
}
for (int index = 0; index < x.length; index++)
{
if (x[index] != y[index])
{
return false;
}
}
return true;
}

Trying to compare the contents two Iterators, how?

EDIT: With your help I managed to fix my problem. I have edited my code to now show how I had to have it set up to get it working.
Currently I am having trouble coding a part which compares the content of two iterators. As part of the requirements for my assignment, I need to use a linkedlist to store the individual characters of the entered String. I have gotten to the point where I have two iterators which would contain the input one way and the reverse way.
String palindrom = input.getText();
String [] chara = palindrom.split (""); //this is successfully splitting them, tested.
int length = palindrom.length( ); // length == 8
System.out.println (length); //can use this for how many checks to do?
LinkedList ll = new LinkedList(Arrays.asList(chara));
Iterator iterator = ll.iterator();
Iterator desIterator = ll.descendingIterator();
/*while(iterator.hasNext() ){
System.out.println(iterator.next() );
}
while(desIterator.hasNext() ){
System.out.println(desIterator.next() );
}*/
boolean same = true;
while(iterator.hasNext()){
if(!iterator.next().equals(desIterator.next())){
same = false;
break;
}
}
And using the System.out I can see that they are being stored correctly, but I don't know how to check if the iterators store the same contents. What would be one of the simplest methods to compare the two iterators or convert them into something I can compare? To clarify I want to verify they contain the same elements in the same order.
boolean same = true;
while(iterator.hasNext()){
if(!desIterator.hasNext() || !iterator.next().equals(desIterator.next())){
same = false;
break;
}
}
System.out.println(same);
You need to iterate over both iterators simultaneously, i.e. with one loop. Here is a general comparison function (0 when equal, < 0 when A < B, > 0 when A > B):
static <T extends Comparable<S>, S> int compare(Iterator<T> a, Iterator<S> b) {
while (a.hasNext() && b.hasNext()) {
int comparison = a.next().compareTo(b.next());
if (comparison != 0) {
return comparison;
}
}
if (a.hasNext())
return 1;
if (b.hasNext())
return -1;
return 0;
}
To just check if they are equal, this can be simplified:
static <T, S> boolean equals(Iterator<T> a, Iterator<S> b) {
while (a.hasNext() && b.hasNext()) {
if (!a.next().equals(b.next())) {
return false;
}
}
if (a.hasNext() || b.hasNext()) {
// one of the iterators has more elements than the other
return false;
}
return true;
}
Guava implements this as Iterators.elementsEqual.
In both answers throw NullPointerException, if iterator.next() == null. This method is more optimal.
public static boolean equals(Iterator i1, Iterator i2) {
if (i1 == i2) {
return true;
}
while (i1.hasNext()) {
if (!i2.hasNext()) {
return false;
}
if (!Objects.equals(i1.next(), i2.next())) {
return false;
}
}
if (i2.hasNext()) {
return false;
}
return true;
}

How can I check whether an array is null / empty?

I have an int array which has no elements and I'm trying to check whether it's empty.
For example, why is the condition of the if-statement in the code below never true?
int[] k = new int[3];
if (k == null) {
System.out.println(k.length);
}
There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Method to check array for null or empty also is present on org.apache.commons.lang:
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.isEmpty(array);
Look at its length:
int[] i = ...;
if (i.length == 0) { } // no elements in the array
Though it's safer to check for null at the same time:
if (i == null || i.length == 0) { }
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null, when you don't new it up.
e.g.
int[] numbers = null; // changed as per #Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.
The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.
I tested as below. Hope it helps.
Integer[] integers1 = new Integer[10];
System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
for (Integer integer : integers1) {
System.out.println(integer); //prints all 0s
}
//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
// integers1[2] = 0;
for (Integer integer : integers1) {
System.out.println(integer); //Still it prints all 0s but it is not empty
//but that manually added 0 is different
}
//Even we manually add 0, still we need to treat it as null. This is semantic logic.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,
public static boolean isEmpty(#Nullable Object[] array) {
return (array == null || array.length == 0);
}
An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty.
Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.
int[] k = new int[3];
if(k.length == 0)
{
//do something
}

Categories