簡體   English   中英

ArrayList沒有打印出來

[英]ArrayList isn't printing out

我創建了兩個數組。 我加了 然后,我想通過定義一個方法來打印出新數組。 但是該方法無法打印出數組。 我的代碼中的錯誤在哪里?

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();

    }

}

您的列表中沒有要打印的內容。 你需要改變

for (String x : l1) // l1 don't have a single element
                    // at this moment 

for (String y : l2) // same as l1 

for (String x : boy)

for (String x : girl) 

再次

 l2.add(y);
 l1.addAll(l2);
 l2 = null; // inside for lopp l2 become null

因此,您將從此處獲得NPE

更正的代碼

  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();
}

for循環遍歷仍然為空的列表。

   for (String x : boys) {
        l1.add(x);
   }

要么

   Collections.addAll(l1, boys);

將l2設置為null不會很好地循環。 並且addAll可以在循環外部完成。

您的List L1L2都為空。 因此,您的兩個for循環主體都不會執行。

公共類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();

}

您不能遍歷任何地方的boy[]girl[]數組。 您需要像for (String x : boy)那樣for (String x : boy)迭代for (String x : boy)獲得某些結果。

您需要遍歷boy []和girl []數組以在其中打印內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM