Решение с использованием только массивов:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[][] arraysList = new String[1][];
String[] array = { "a", "b", "c", "ab", "cd", "abc", "abcde", "fghij", "klmno" };
int srcPos, row = 0;
for (int i = 0; i < array.length; i++) {
srcPos = i;
while (i < array.length - 1 && array[i].length() == array[i + 1].length()) {
i++;
}
// Create a new array to store the current set of strings of equal length
String[] subarray = new String[i - srcPos + 1];
// Copy the current set of strings of equal length from array to subarray[]
System.arraycopy(array, srcPos, subarray, 0, subarray.length);
// Assign subarray[] to arraysList[][]
arraysList[row++] = subarray;
// Copy arraysList[][] to temp [][], increase size of arraysList[][] and restore
// arrays from temp [][] to arraysList[][]
String[][] temp = arraysList;
arraysList = new String[row + 1][subarray.length];
for (int j = 0; j < temp.length; j++) {
arraysList[j] = temp[j];
}
}
// Drop the last row which was created to store a new subarray but there was no
// more subarrays to store and therefore it is empty.
arraysList = Arrays.copyOf(arraysList, arraysList.length - 1);
// Display the subarrays
for (String[] arr : arraysList) {
System.out.println(Arrays.toString(arr));
}
}
}
Выход:
[a, b, c]
[ab, cd]
[abc]
[abcde, fghij, klmno]
Решение с использованием List
и массива:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String[]> list = new ArrayList<String[]>();
String[] array = { "a", "b", "c", "ab", "cd", "abc", "abcde", "fghij", "klmno" };
int srcPos;
for (int i = 0; i < array.length; i++) {
srcPos = i;
while (i < array.length - 1 && array[i].length() == array[i + 1].length()) {
i++;
}
String[] subarray = new String[i - srcPos + 1];
System.arraycopy(array, srcPos, subarray, 0, subarray.length);
list.add(subarray);
}
// Display the subarrays
for (String[] arr : list) {
System.out.println(Arrays.toString(arr));
}
}
}
Выход:
[a, b, c]
[ab, cd]
[abc]
[abcde, fghij, klmno]