This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Question  RSS feed

 
Mohammed Malik
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, please look at the code below:-

---------------------------------
public class a { // comparing 2 arrays
public static void main (String args[]) {

int array1 [] = {1,2}; // array1
int array2 [] = {1,2}; // array2

if (array1 == array2) System.out.println("same");

} // ~main()
} // ~class
---------------------------------

1. Why doesn't it print same?
2. Also, how do I compare these 2 arrays so that I can make it print same?
3. Ideally, I want to compare 2 elements AT THE SAME TIME, eg 2 for loops won't work as they only let me compare ONE element at a time - I need to be able to compare 2 (& more) elements at a time - Does anyone know how to do this?

Any help with this problem will be greatly appreciated. Many thanks.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are objects and array1 and array2 are references to two different objects.

So when you compare them with ==, you get false.

There is a utility method in java.util.Arrays that will let you compare the contents of arrays.
 
Mohammed Malik
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Keith Lynn:
Arrays are objects and array1 and array2 are references to two different objects.

So when you compare them with ==, you get false.

There is a utility method in java.util.Arrays that will let you compare the contents of arrays.


Thanks for the reply. Yeah, I've used the arrays quite alot in the past & remember there's a method for comparing, but still it doesn't let me compare 2 elements at a time. Eg, say I have:-

array1 = {1,1};
array2 = {1,1,2,2,2,1,1};

And I want to find how many times {1,1} occurs in array2 (should occur twice), there is nothing that let's me do that - Two for loops will tell me that '1' occurs four times in array2, but this isn't what I want to do - I want to see how many times {1,1} occurs in array2..
 
Fahd Shariff
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A quick hack would be to convert both arrays to string representations and then use methods like indexOf or substring that come in the String class.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!