2013-03-15 102 views
4

我是一名自學者。目前,我正在製作一個GUI項目,我需要一個矩陣類型的數據庫。如何創建可存儲多個對象的ArrayList類?

我想了解如何創建一個類,可以存儲多個對象在arraylist中。

這是我的示例代碼。請注意,這只是我的嘗試。這段代碼沒有最終確定,並且不起作用。

謝謝你的幫助。

import java.util.ArrayList; 
    import java.util.List; 

}}

+0

所以基本上你要存儲用戶信息'ArrayList'? – kaysush 2013-03-15 02:03:14

+0

本示例要求您創建一個名爲User的類來封裝有關用戶的數據。一旦你創建了一個User類,你可以創建一個ArrayList的Users。這是面向對象編程中的一個重要概念。 – jahroy 2013-03-15 02:24:37

+0

SuKu:是的。 Jahroy:謝謝你的建議。 – user1799252 2013-03-15 02:32:51

回答

9

我認爲更好的方式來做到這一點是創建一個用戶信息類來存儲這樣的特定用戶的信息。

// I made them all public but this might not be a good idea! 
class UserInfo { 
    String user; 
    String pass; 
    String secretCode; 
} 

然後你把它放到一個ArrayList中。

ArrayList <UserInfo> InfoList = new ArrayList<UserInfo>();  

然後你目前的方法,你可以做

// Not so sure what you want to do in this method... so you get to figure out that yourself! 
public void userInternalDatabase (UserInfo info) { 

    this.user = info.user; 
    this.pass = info.pass; 
    this.secretCode = info.secretCode; 
} 

public void addUser(String i, String j, String k) { 
    UserInfo newUser = new UserInfo(); 
    newUser.user = i; 
    newUser.pass = j; 
    newUser.secretCode = k; 
    InfoList.add(newUser); 
} 

public Object findUsername(String a) 
{  
    for (int i=0; i <InfoList.size(); i++) { 
     if (InfoList.get(i).user.equals(a)){ 
      return "This user already exists in our database."; 
     } 
    } 
    return "User is not founded."; // no Customer found with this ID; maybe throw an exception 
} 
+0

謝謝你的幫助。 因此,如果我想檢索用戶名數據,我該怎麼辦?另外,InfoList會有三列:用戶名,密碼和密碼?謝謝。 – user1799252 2013-03-15 02:28:04

+0

你可以使用InfoList.get(index)索引是一個整數來檢索一個UserInfo對象,或者你可以使用迭代器來搜索與你正在搜索的信息相同的對象。您可以使用InfoList.get(i).user,InfoList.get(i).pass,InfoList.get(i).secretCode訪問數據。再次請注意,公共變量可能不是一個好主意! – cwhsu 2013-03-15 02:32:08

+1

好的。非常感謝你。 – user1799252 2013-03-15 02:34:49