[英]ArrayList isn't printing out
I have created two arrays. 我创建了两个数组。 I added them up.
我加了 Then I wanted to print out the new array by defining a method.
然后,我想通过定义一个方法来打印出新数组。 But the method can't print out the array.
但是该方法无法打印出数组。 Where is the error in my code?
我的代码中的错误在哪里?
package stringpractice;
import java.util.LinkedList;
import java.util.List;
public class StringPractice {
public static void main(String[] args) {
String[] boy = {"John", "Russel", "Ryan"};
List<String> l1 = new LinkedList<String>();
for (String x : l1) {
l1.add(x);
}
String[] girl = {"Sara", "Leena", "Emilia"};
List<String> l2 = new LinkedList<String>();
for (String y : l2) {
l2.add(y);
l1.addAll(l2);
l2 = null;
printMe(l1);
/*removeStuff(l1, 1,2);
reverseMe(l1);
*/
}
}
public static void printMe(List<String> l1) {
for (String p : l1) {
System.out.printf("%s ", p);
}
System.out.println();
}
}
There is nothing to print in your list. 您的列表中没有要打印的内容。 You need to change
你需要改变
for (String x : l1) // l1 don't have a single element
// at this moment
and 和
for (String y : l2) // same as l1
To 至
for (String x : boy)
and 和
for (String x : girl)
Again 再次
l2.add(y);
l1.addAll(l2);
l2 = null; // inside for lopp l2 become null
So you will get NPE
from here. 因此,您将从此处获得
NPE
。
Corrected code 更正的代码
public static void main(String[] args) {
String[] boy = {"John", "Russel", "Ryan"};
List<String> l1 = new LinkedList<>();
for (String x : boy) {
l1.add(x);
}
String[] girl = {"Sara", "Leena", "Emilia"};
List<String> l2 = new LinkedList<>();
for (String y : girl) {
l2.add(y);
l1.addAll(l2);
printMe(l1);
}
l2 = null;
}
public static void printMe(List<String> l1) {
for (String p : l1) {
System.out.printf("%s ", p);
}
System.out.println();
}
The for-loops walk through the still empty lists. for循环遍历仍然为空的列表。
for (String x : boys) {
l1.add(x);
}
Or 要么
Collections.addAll(l1, boys);
Setting l2 to null will not loop well. 将l2设置为null不会很好地循环。 And the addAll can be done outside the loop.
并且addAll可以在循环外部完成。
your both the List
L1
and L2
are empty. 您的
List
L1
和L2
都为空。 so your both the for
loop body is not executed. 因此,您的两个
for
循环主体都不会执行。
public class StringPractice { public static void main(String[] args) { 公共类StringPractice {公共静态void main(String [] args){
String[] boy = { "John", "Russel", "Ryan" };
List<String> l1 = new ArrayList<String>(Arrays.asList(boy));
String[] girl = { "Sara", "Leena", "Emilia" };
List<String> l2 = new ArrayList<String>(Arrays.asList(girl));
l1.addAll(l2);
l2 = null;
printMe(l1);
/*removeStuff(l1, 1,2);
reverseMe(l1);
*/
}
public static void printMe(List<String> l1) {
for (String p : l1) {
System.out.printf("%s ", p);
}
System.out.println();
}
You arent traversing the boy[]
and girl[]
array anywhere. 您不能遍历任何地方的
boy[]
和girl[]
数组。 You need to iterate like for (String x : boy)
for some result. 您需要像
for (String x : boy)
那样for (String x : boy)
迭代for (String x : boy)
获得某些结果。
您需要遍历boy []和girl []数组以在其中打印内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.