2012-02-22 139 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语言和标准库中的基本教程。