• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to check if the elements in one array are present in another array  RSS feed

 
Pooja Patole
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,

I have two arrays. I want to check if the elements in one array are presents in other array.How should i do this?

Please help
Pooja
 
E Armitage
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What have you tried?
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are numerous ways to do this:
1) Take an element from array, and iterate over other array to see if that element is present. Do this process for all arrays.
2) Sort both arrays to reduce number of comparisons (well, actually, number of comparisons are more if we consider those required during sorting )
3) Convert an array into list and call 'contains' method of it.
And so on.

I would suggest to first work with pencil and paper (i.e. algorithm). Write down and try to understand each and every step of the logic, and then go for coding it.

I hope this helps.
 
Pooja Patole
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I've tried this and it works.Is this fine or can i improve the code more??

 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Copy the two arrays into Sets and use some of the methods of the Set interface.
 
Eshwin Sukhdeve
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dont check with != juct check with == if it is equal just come out of loop using break;
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code does not do what you think it does. In particular, if only one element is common between the two arrays, the behavior is the same as when all elements are the same. Further, an exception is thrown if the arrays are not the same size.

Four suggestions: 1. check your inner loop very carefully; 2. please use braces in if/else blocks to improve readability; 3. test your code with arrays of various lengths and different contents; 4. consider very carefully the meaning of the break statement in your else branch.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eshwin Sukhdeve wrote:dont check with != juct check with == if it is equal just come out of loop using break;

Except == or != shouldn't be used for comparing Strings, which is what I assume is inside the Names arrays.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!