0

I want to get the common values of list1 and compare it to list2. I got an output of 11121 instead of 121. How can I resolve this?

Here's my code:

public class TwoLists {

    static void arrs() {
        int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
        int[] list2 = {1, 2, 1};
    
        for(int i = 0; i < list1.length-1; i++)
        {
            for(int o = i+3; o < list1.length; o++)
            {
                for(int out1 = list1[i]; out1 == list1[o]; out1++)
                {
                    System.out.print(out1);
                    }
                }
            }
        }


    public static void main(String[] args)
    {
        arrs();
    }

}
3
  • 1
    I do not understand what you want to do. Maybe add some expected input and output? Also, list2 is never used in your code, is this correct? Commented Oct 2, 2020 at 23:22
  • Does this answer your question? finding common elements in two integer arrays java Commented Oct 2, 2020 at 23:25
  • Oh, I forgot. I stuck at list1 first :/ Commented Oct 2, 2020 at 23:25

1 Answer 1

0

Try the following:

  • Use a Set<Integer> to record those already found.
  • then use a nested array going from start to finish for each array
  • in the outer loop, see if set.contains() the current value.
  • if so, continue outer loop.
  • otherwise, compare inner and outer list values.
  • when a match is found, print it, add to the set, and then break out of the inner loop.
  • continue next value in outer loop.

There are other, faster ways using just sets exclusively but this would serve as a start.

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

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.