簡體   English   中英

ArrayList-可以讀出元素名稱嗎?

[英]ArrayList - possible to read out the element name?

大家好!

我的項目更大,所以我決定將其簡短一點,只顯示我當前擁有的問題代碼。 首先,在控制台上進行即時編程。 從掃描儀讀取六個字符串,然后將它們保存到變量中,然后進行有效性檢查(長度,特殊符號等)。 因此,我決定使用額外的方法check_newCustomer()來完成此操作。 我使用ArrayList作為一個值返回更多值。 現在,我需要在main()函數或任何其他將新客戶寫入數據庫的方法中捕獲輸入。 現在的問題是我不知道如何在其他方法中引用userID,firstname,secondname...。 我可以參考一個索引。 但是當我可以使用變量名來引用它時,我會更喜歡它。 因此,使用其他方法處理字符串要容易得多。 可能?

public static void main(String[] args) {
    ArrayList<String> newCustomer = new ArrayList<String>(); 
    check_newCustomer (newCustomer);
}


public static void check_newCustomer(ArrayList<String> newCustomer) throws IOException {
    String userID = null;
    String firstname = null;
    String secondname = null;
    String street = null;
    String zipcode = null;
    String city = null;

    // validity check before I fill the input fields
    ...

    // fill arraylist
    newCustomer.add(userID);
    newCustomer.add(firstname);
    newCustomer.add(secondname);
    newCustomer.add(street);
    newCustomer.add(zipcode);
    newCustomer.add(village);
}

謝謝!

不, ArrayList的值只是一個參考。 您最初使用其他變量引用它的事實是無關緊要的。

可以使用Map<String, String>代替...但是擁有一個Customer類,其中包含用於各種信息的字段會清潔。 如果需要多個客戶,則可以有一個List<Customer>

一個人需要創建一個類Customer,只需一組字段即可。 而不是字符串列表。

public class Customer {
    String userID;
    String firstname;
    String secondname;
    String street;
    String zipcode;
    String city;
}

並在代碼中:

Customer newCustomer = new Customer();
newCustomer.userID = ....
System.out.println(newCustomer.userID);

當您通過check_newCustomer (newCustomer); 您只傳遞數組列表的副本。 在這種情況下,原始數組列表newcustomer保持原樣,而范圍在方法check_newCustomer內的新副本將存儲所有字符串。 您可以為客戶創建一個新類,也可以創建一個類並將數組列表作為類變量,將check_newCustomer作為類方法。 在后一種情況下,這很簡單。

    class customer
        ArrayList<String> newCustomer;
        public static void main(String[] args) {

                newCustomer = new ArrayList<String>(); 
                check_newCustomer ();
            }


        public static void check_newCustomer() throws IOException {
                String userID = null;
                String firstname = null;
                String secondname = null;
                String street = null;
                String zipcode = null;
                String city = null;

                // validity check before I fill the input fields
                ...

                // fill arraylist
                newCustomer.add(userID);
                newCustomer.add(firstname);
                newCustomer.add(secondname);
                newCustomer.add(street);
                newCustomer.add(zipcode);
                newCustomer.add(village);
                }
}

這必須工作。

暫無
暫無

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

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