0

I am trying to compare two arrays of objects to verify that they have the same values. It is returning false when it should be returning true. Im not sure what I am doing wrong when comparing the two arrays.

Class : arrayObject

import java.util.*;


public class arrayObject {

	private int initializedInt;
	private boolean equals;
	private int[] one, two;
	
	arrayObject(){
		
	}
	arrayObject(int x){
		initializedInt = x;
	}
		
	public int getInt(){
		return initializedInt;
	}
	
	public boolean equals(arrayObject[] one,arrayObject[] two, int sizeOfArray){
		equals = Arrays.equals(one, two);
		//while(equals){
			/*for (int i = sizeOfArray; i !=0; i--){
				one[i].equals(two[i]);
				return equals;
				}*/
		//}
		return equals;
	}
}

Class : Main

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int sizeOfArray = 3;

		arrayObject arrayEqualsMethodTest = new arrayObject();
		arrayObject[] array1 = new arrayObject[sizeOfArray];
		arrayObject[] array2 = new arrayObject[sizeOfArray];
		System.out.print("Array1 can be resolved to {");
		
		for(int i = 0; i != 3; i++){
			array1[i] = new arrayObject(4);
			System.out.print(array1[i].getInt() + ",");
			
		}
		System.out.print("}");
		
		System.out.print("\nArray2 can be resolved to {");
		for(int i = 0; i != 3; i++){
			array2[i] = new arrayObject(4);
			System.out.print(array2[i].getInt() + ",");
			
		}
		System.out.print("}");
		
		System.out.println("\nDoes array1 equal array2? " + Arrays.equals(array1, array2));
		
		System.out.println("That doesn't seem right. Lets run it through an equals method!\n"
							+ "Does array1 equal array2 when run through the method? " 
							+ arrayEqualsMethodTest.equals(array1, array2, sizeOfArray));

	}

}
2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by mcriscolo
0

Ah, but they don't have the same *values* - you are constructing arrays of *objects*. Now, the objects may contain the same values, but that's it. Each object is different. You can either change over and make the arrays out of integers, or provide a comparison function that, when you go to compare the arrays, checks each element and compares the values contained in each object at each position.

Your commented-out function in the first chunk of code was almost correct - if you change that to call your "getInt()" property on each object in the arrays, you should have it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.