/ Published in: Java
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.
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
public static <T> int indexOfSubArray(T[] array, T[] subarray){ if (array == null || subarray == null) return -1; } public static int indexOfSubArray(int[] array, int[] subarray) { return indexOfSubArray(toObjectArray(array), toObjectArray(subarray)); } // Alternatively use commons lang ArrayUtils to convert it into an array of objects if (array == null) return null; for (int i=0; i<array.length; i++) return result; }