Answer question 2

/ Published in: Java
Save to your folder(s)

I assume that the arrays have to be of the same type.

I have decided to use the method indexOfSubList provided by the Collections class as a way of simplifying our code. This method does exactly what is required, but for lists.

The main issue with the method is that it doesn't support arrays of primitives, so we need to create additional methods for each primitive (int, long, double, etc) where the array of primitives gets transformed into an array of objects.
In the example below only int is implemented.

This might have a performance impact on some scenarios because of the conversion of arrays to lists, I suppose the impact is mainly for arrays of primitives.

However the code remains simpler, and probably the implementation of the indexOfSubList method in the Collections class is quite efficient.

Some unit tests should be developed to test if the performance is acceptable.

As we can see the code of indexOfSubArray methods below is quite concise.

Copy this code and paste it in your HTML
  1. public static <T> int indexOfSubArray(T[] array, T[] subarray){
  2. if (array == null || subarray == null) return -1;
  3. List<T> list = Arrays.asList(array);
  4. List<T> subList = Arrays.asList(subarray);
  5. return Collections.indexOfSubList(list, sublist);
  6. }
  8. public static int indexOfSubArray(int[] array, int[] subarray) {
  9. return indexOfSubArray(toObjectArray(array), toObjectArray(subarray));
  10. }
  12. // Alternatively use commons lang ArrayUtils to convert it into an array of objects
  13. private static Integer[] toObjectArray(int[] array) {
  14. if (array == null) return null;
  15. Integer[] result = new Integer[array.length];
  16. for (int i=0; i<array.length; i++)
  17. result[i] = new Integer(array[i]);
  18. return result;
  19. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.