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);
}
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. Commented Mar 14, 2022 at 8:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

For the greatest common divisor (mentioned as a side-note by the OP), multiple occurrences are essential. So, the Set approach won't work.
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.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.