这是作业吗?
所以你有一个字符串数组,你想用它创建一个 List>,每个内部 List 最多包含 x 个元素。
要获取 x 个元素并将它们放入一个列表中,您可以执行一个简单的 for 循环。
String[] myStringArray = { ... };
List<String> myListOfString = new ArrayList<>();
for(int i=0; i<x; i++) {
myListOfString.add(myStringArray[i]);
}
例如,如果你有这些值
String[] myStringArray = {"a", "b", "c", "d", "e"};
x = 2;
您将使用上述循环获得以下列表:
["a", "b"]
太棒了!但是我们需要得到myStringArray的所有内容!我们如何做到这一点?然后我们做第一步,我们遍历数组的所有内容。我们可以这样做。
int i=0;
while(i < myStringArray.length) {
System.out.println(myStringArray[i]);
i++;
}
将输出:
a
b
c
d
e
这并不能解决问题……但至少我们知道如何迭代整个事情。下一步是获取其中的 x 个。听起来很简单吧?所以基本上我们需要从内容中创建一个 x 列表。也许我们可以使用我们创建几个示例的逻辑来解决问题。
// Create list of list of string here
int i = 0;
while(i < myStringArray.length) {
// Create list of string here
for(int j=0; j<x; j++) {
// Add myStringArray[j] to list of string here
}
// Add the list of string to the list of list of string here
i++;
}
简单吧?不,这给出了以下列表:
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
为什么?在第一个循环中,我们迭代到数组中有多少。在第二个循环中,我们将元素 0 和 1 添加到列表中。显然它是行不通的。第二个循环需要知道它不应该添加以前添加的元素,同时第一个循环需要知道第二个循环在做什么。所以你可能会想,也许我们可以使用int i 来指示第二个循环应该从哪里开始?
int i = 0;
while(i<myStringArray.length) {
while(i<x) {
// add myStringArray[i];
i++;
}
i++;
}
不幸的是,使用与以前相同的值,这只会给出以下列表
["a", "b"]
因为i 正在遍历整个数组。因此,当它从 0 变为长度时,无论 i 的值在第二个数组上使用什么。再次循环时,i 变为 1,所以第二次循环的开始是 1。
我们需要一个单独的变量来进行计数,同时仍然记住我们当前在第二个循环中的位置。
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x) {
// Add myStringArray[count+i] to list of string
count++;
}
// Add to list of list of string
i += count + 1; // Need to be aware of how much we have processed
}
这将做我们想要的,但不幸的是,我们可能会在某些值上遇到麻烦。假设 x 为 10,myStringArray 的长度仅为 2。这将引发异常,因为当它到达 count+i = 3 时,该索引不再存在。第二个循环还需要知道还剩下多少。
最后我们将得到以下代码
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x && count+i < myStringArray.length) {
// Add myStringArray[count+i] to list of string
}
// Add to list of list of string
i += count; // Need to be aware of how much we have processed
}
这会给你
["a", "b"]
["c", "d"]
["e"]
编辑:下次尝试放一些你尝试过的代码。