2012-02-22 144 views
-2

我在分配數組列表中的值時遇到一些困難。我的代碼是:將結果添加到數組列表

while (answer.hasMore()) { 
    SearchResult rslt = (SearchResult)answer.next(); 
    Attributes attrs = rslt.getAttributes(); 
    System.out.println(); 
    if (attrs.get("department") != null && attrs.get("telephonenumber") != null) { 
     System.out.println(attrs.get("department") + " " + attrs.get("name") + " " + 
         attrs.get("Description") + " " + attrs.get("mail") + " " + 
         attrs.get("telephonenumber")+ 
         attrs.get("samaccountname") + attrs.get("samaccountname")); 
} 

我想每一個attrs.get("department") + attrs.get("description")+ attrs.get("name")+attrs.get("mail")的值賦給一個數組列表。

我想在開始時就確定:

String[] name = new String[100]; 

,並在while循環我試圖讀取name屬性,我試圖做的:

name = attrs.get("name"); 

但沒有奏效。任何人都可以幫忙

+0

通過做的工作,你的意思是編譯失敗?我懷疑'attrs.get()'返回一個'String'? – hmjd 2012-02-22 21:05:38

+0

'attrs.get(「name」);'返回一個字符串?您不能將字符串分配給字符串數組。你可能想要編輯你的問題來表明你真的想要做什麼,因爲將不同的屬性分配給同一個數組真的沒什麼意義。 – Perception 2012-02-22 21:05:42

回答

1

您不能直接將字符串分配給由字符串「references」組成的數組。你需要先索引它。但是實際使用列表會更好(也可能稍後將其轉換爲數組)。在Java文檔中查看ListArrayList

舉個例子:

Attributes attrs = new Attributes(); 
    List<String> attribValues = new ArrayList<String>(); 
    System.out.println(); 
    if (attrs.get("department") != null 
      && attrs.get("telephonenumber") != null) { 
     System.out 
       .println(attrs.get("department") + " " + attrs.get("name") 
         + " " + attrs.get("Description") + " " 
         + attrs.get("mail") + " " 
         + attrs.get("telephonenumber") 
         + attrs.get("samaccountname") 
         + attrs.get("samaccountname")); 
     attribValues.add(attrs.get("department")); 
     attribValues.add(attrs.get("telephonenumber")); 
    } 

    final String[] attribArray = attribValues.toArray(new String[attribValues.size()]); 
+0

你能否在上面的例子中幫助一下 – user1080320 2012-02-22 21:07:48

1

首先定義你的名字作爲字符串而不是字符串數組是這樣的:

String name; 

,然後讀名稱:

name = attrs.getString("name"); 

現在回到你填寫List的問題,我相信你會在這裏得到現成的答案,但我建議你做一些閱讀如何在Java中創建和填充List。

2

在Java中,數組和ArrayList完全不同。

String[] name_array = new String[100]; 

創建字符串的一個固定長度的陣列,但

ArrayList name_list = new ArrayList(); 

創建的對象的一個​​可變長度的ArrayList(它將成長爲您添加更多對象)。

要將對象添加到ArrayList,可以使用其方法add()

name_list.add("Hello"); 

然而,隨着一個數組,你需要設置對象在特定的指數,e.g:

name_array[23] = "Hello"; 

你需要閱讀的Java語言和標準庫中的基本教程。