I need to create a method to check the elements of two arrays and determine if they are equal..
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
I need to create a method to check the elements of two arrays and determine if they are equal..
If the order matters as well, you can do it manually by iterating through each array comparing each value at position x, or using the Class Arrays equals function. If the arrays may be out of order you can do it manually by taking each value in the first array, and searching the second for that value, returning false if it cannot be found, or true at the end of the iteration if all were found. Alternatively, you could sort the arrays and use the Arrays object to compare
The order is not important all, Here is what i have tried using but i get an illegal start to expression error
for the if statement... Please help me set something up im really lost...
boolean check = Arrays.equals(setA, setB);
if (check == true){
System.out.println("Arrays are same.");
else
System.out.println("Both Arrays are not same.");
}
You are missing a pair of brackets in the code you posted. Be careful if order does not matter and you wish to check if each array contains the same SET of values (as opposed to SET and SEQUENCE), for example consider the following arrays:
int array1[] = {1,2,3,4};
int array2[] = {1,2,3,4};
int array3[] = {2,1,3,4};
Arrays.equals() will return true when comparing array1 and array2, but false when comparing array1 to array3 - even though thesy contain the same values (because they are out of order).
If you are truly confused, I recommend going back to the basics
Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)
I understand that part. Now what if the elements within the array are read in by using a scanner(user input). I can i compare those elements which i do not know or are not fixed.