2

I am having problems at the moment of initialize the array and returning it. The method is suppose to return common items of a generic array, but i cant initialize array "a" or returning it. Any advice??

public static <T> T[] commonItems( T[] arr1, T[] arr2)
{
    T[] a;
    int pos = 0;
    for( int i = 0; i < arr1.length; i++)
    {
        for(int j = 0; j < arr2.length; j++)
        {
           if(arr1[i].equals(arr2[j]))
           {
               a[pos] = arr1[i];
               pos++;
           }
        }
    }
    return a;
}

1 Answers1

2

You don't know in advance how many elements are common, so in the first step it is best to collect the common items in a list:

public static <T> T[] commonItems( T[] arr1, T[] arr2)
{
     ArrayList<T> list = new ArrayList<>();
     for (int i = 0; i < arr1.length; i++)
     {
          for( int j = 0; j < arr2.length; j++)
          {
              if (arr1[i].equals(arr2[j]))
                  list.add(arr1[i]);
          }
     }

Then you can create the result array, using Class.getComponentType:

     T[] result = (T[])Array.newInstance(arr1.getClass().getComponentType(), list.size());
     list.toArray(result);
     return result;
}
wero
  • 30,527
  • 3
  • 46
  • 72
  • Thank you for you recommendations and advises, it really helped. – Omar Gonzalez Nov 20 '15 at 04:18
  • @newacct not clear to me what you mean. How do you call `commonItems` passing a `String[]` and `Integer[]` array? – wero Nov 24 '15 at 08:06
  • @newacct you can call `commonItem(stringarray, integerarray);` and it will compile (`T` is `Object&Comparable&Serializable`). It will not exactly fail but return an empty string array. But if you write `String[] s = commonItem(stringarray, integerarray)` it will not compile: So I don't exactly get your point. – wero Nov 24 '15 at 08:24