簡體   English   中英

如何訪問ArrayList中的ArrayList? Java的

[英]How to access an ArrayList in an ArrayList? Java

首先讓我告訴你我想做什么。 該程序應要求輸入密碼,然后為密碼的每個字符創建數組列表。 然后,這些列表將被添加到整個數組列表。(mylist)問題是我該如何使用字符串值填充ArrayList? 當所有數組列表都填充后,我希望能夠按字母順序對其進行排序。 代碼打擊。

// Creating ArrayLists
ArrayList<ArrayList<String>> mylist = new ArrayList<ArrayList<String>>();
List<String> mycode = new ArrayList<String>();    
char[] test;
String mypassword;

System.out.println("Pleaseinput your passphrase");
        // Getting user input (Password)
        Scanner in = new Scanner(System.in);
        mypassword = in.nextLine();
        // Storing password in character array
        test= mypassword.toCharArray();

    // Beginning for loop to create array lists for each character
    // in the password
    for (int i = 0; i < mypassword.length(); i++) { 
            mycode = new ArrayList<String>();
            // Here I'm trying to give the created Arraylist (mycode)
            // a name or value of the character the for loop is at so I                  can order it alphabetically later.
            mycode.equals(test[i]);
            // Adds the array list.
            mylist.add((ArrayList<String>) mycode);
        }

預先感謝您對我的問題的任何建議。

從注釋中假定,您只想將String轉換為List<String> ,其中每個字符都是String ,但要使每個字符作為列表中的第一個元素,而讓“ hello”作為列表中的第二個元素q ...

public static void main(String[] args) {
    // Creating ArrayLists
    List<List<String>> mylist = new ArrayList<>();
    String mypassword;

    System.out.println("Pleaseinput your passphrase:");
    // Getting user input (Password)
    Scanner in = new Scanner(System.in);
    mypassword = in.nextLine();

    // Beginning for loop to create array lists for each character
    // in the password      
    for (int i = 0; i < mypassword.length(); i++) { 
        List<String> firstCharAndMore = new ArrayList<>();
        char c = mypassword.charAt(i);
        firstCharAndMore.add(String.valueOf(c));
        if ('q' == c) {
            firstCharAndMore.add("hello");
        }
        mylist.add(firstCharAndMore);
    }
    System.out.println(mylist.toString());
}

輸入qwertyqwerty輸出: [[q, hello], [w], [e], [r], [t], [y], [q, hello], [w], [e], [r], [t], [y]]

暫無
暫無

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

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