public static void main(String[] args) {
Integer[] courses1 = {1,2,3};
Integer[] courses2 = {0,1};
Integer[] longestArr;
Integer[] shortestArr;
ArrayList commonCourses = new ArrayList();
if ( courses1.length > courses2.length)
{
longestArr = courses1; shortestArr = courses2;
}
else
{
longestArr = courses2; shortestArr = courses1;
}
for ( int i : longestArr)
{
for ( int j : shortestArr)
{
if (i == j);
commonCourses.add(i);
}
}
Collections.sort(commonCourses);
System.out.println(commonCourses.size());
}
No matter what the values of course1 and courses2, the arrayList commonCourses always has a size of one more the the total number of elements in both arrays when it is supposed to only contain the elements that are in both arrays.
I have 2 questions why is ever element from the 2 arrays being added to the arrayList and why is the size of the arrayList always one more than the total number of elements?
If you are wondering why I have courses1 and courses2 declared at the start, this is a problem from talentBuddy.co that I'm testing on eclipse. I have tested with different starting conditions and the same thing always happens.
My new slimmed down solution
public static void main(String[] args) {
Integer[] courses1 = {1};
Integer[] courses2 = {0};
ArrayList <Integer>commonCourses = new ArrayList<Integer>();
for ( int i : courses1)
{
for ( int j : courses2)
{
if (i == j)
commonCourses.add(i);
}
}
Collections.sort(commonCourses);
System.out.println(commonCourses.size());
}