-2

I'm writing a method that finds intersection of given arrays.

Since I had to iterate both arrays, I was thinking of using

if(arr2.length > arr1.length){
     intersection(arr2, arr1);
}

The reason I came up with this idea was that it seemed to me to be the better way to reduce the length of code for handling arrays that have different length.

As a newbie to programming, I'm wondering if there is any other suggestion.

chalitha geekiyanage
  • 6,464
  • 5
  • 25
  • 32
Lebanner
  • 77
  • 1
  • 1
  • 9
  • 1
    Let `intersection` determine which array is longer, it'll prevent misuse of the method. Otherwise, anyone using that method will have to perform that check (an extra line of code anytime someone wants to use your method), and even after performing it, they could still input the arguments in the wrong order – Vince Sep 18 '16 at 15:45
  • Is there an ´if (arr1.length > arr2.lenght) {intersection(arr1, arr2);}´ equivalent? – Bálint Sep 18 '16 at 15:45
  • Instead of doing if(arr1.length > arr2.length){ do something} else{ do something} – Lebanner Sep 18 '16 at 15:47
  • I wanted to keep the first argument always bigger than the second one. – Lebanner Sep 18 '16 at 15:50
  • 3
    It shouldn't matter which argument is bigger. You should make your method as easy to use as possible. That means making it hard to misuse. Why does it matter which argument has the longer array? That only creates the possibility of users specifying the arguments in the wrong way, which can easily be avoided by checking the lengths within the method. "*it seemed to me to be the better way to reduce the length of code for handling arrays that have different length.*" - performing the check inside the method is the best way. – Vince Sep 18 '16 at 15:54

1 Answers1

0

Put your array in a list:

List a = List.asArray(arr1);

(ref: https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)

And use the suggestion here to find the intersection:

How to do union, intersect, difference and reverse data in java

Community
  • 1
  • 1
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31