0

List A={2,3,3} List B={2,3,5}

I want to get only {2,3} to do the gcd

I tried to use retainall() but result is {2,3,3}

public static int gcd(ArrayList<Integer> A,ArrayList<Integer> B)
{ //A={2,3,3},B={2,3,5}
    A.retainAll(B);
    System.out.println(A);
}
Moomin H
  • 3
  • 1
  • 1
    You haven't specified the task clearly enough, that multiple occurrences in both lists are essential, e.g. from `{2,3,3,5}` and `{3,3,7}` you expect `{3,3}`. So, you're getting answers that are correct, but won't help you. – Ralf Kleberhoff Mar 14 '22 at 08:53

2 Answers2

2

I suggest to make use of Set, e.g. HashSet.

https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/HashSet.html

In a set, there are no duplicate values.

Set<Integer> set = new HashSet<Integer>(A.retainAll(B));

Also, method params use lowerCase naming.

Remo
  • 1,112
  • 2
  • 12
  • 25
  • For the greatest common divisor (mentioned as a side-note by the OP), multiple occurrences are essential. So, the `Set` approach won't work. – Ralf Kleberhoff Mar 14 '22 at 08:50
  • Thx, for pointing out, I am aware of this. Out of the question (well there is not even a clear one), I only got that the author needed a distinct result out of 2 Array lists. – Remo Mar 14 '22 at 08:59
0

you can use contains(Object o) method. Returns true if this list contains the specified element. ArrayList

Derrick
  • 3,669
  • 5
  • 35
  • 50
Abaytan99
  • 1
  • 2