Java 字符串数组:在循环中添加元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20921281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:20:13  来源:igfitidea点击:

String array : Adding elements in Loop

javaloopsarrays

提问by aizaz

Here is my code

这是我的代码

LDAPAttributeSet attributeSet = new LDAPAttributeSet();

String rolesName;
String uniquemem[] = rolesName.split(",");

if (uniquemem.length == 1)
    attributeSet.add(new LDAPAttribute("uniqueMember",
                        new String[] { "cn="+uniquemem[0]}));

if (uniquemem.length == 2)
    attributeSet.add(new LDAPAttribute("uniqueMember",
                        new String[] {
                                "cn=" +uniquemem[0],   
                                "cn=" + uniquemem[1]
                                    }));
if (uniquemem.length == 3)
    attributeSet.add(new LDAPAttribute("uniqueMember",
                        new String[] {
                                "cn=" + uniquemem[0]
                                        ,
                                "cn=" + uniquemem[1]
                                         ,
                                "cn=" + uniquemem[2]
                                          }));

I have tried by using List<String>and StringBufferin forloop to add/append content dynamically but it is accepting only String[]. Please help me solve this issue

我曾尝试通过使用List<String>StringBufferforloop 动态添加/追加内容,但它只接受 String[]。请帮我解决这个问题

I have tried this

我试过这个

StringBuffer sb=new StringBuffer()
            for(int i=0;i<uniquemem.length;i++)
            {
                sb.append("cn=" + uniquemem[i]);
            }

attributeSet.add(new LDAPAttribute("uniqueMember",sb.toString()));

采纳答案by Merlin

What about this..

那这个呢..

LDAPAttributeSet attributeSet = new LDAPAttributeSet();

String rolesName;
String uniquemem[] = rolesName.split(",");

String item = null;
String arrayItems[uniquemem.length]

for(int i=0; i<uniquemem.length; i++) {
    item = "cn=" + uniquemem[i];
    arrayItems[i] = item;
}


attributeSet.add(new LDAPAttribute("uniqueMember", arrayItems);

回答by watery

This will give you the String array you need:

这将为您提供所需的字符串数组:

ArrayList<String> memList = new ArrayList<>(uniquemem.length);
for(int i = 0; i < uniquemem.length; i++) {
    memList.add("cn=" + uniquemem[i]);
}
memList.trimToSize();
memList.toArray(String[0]);
String[] memArray = memList.toArray(new String[memList.size()]);

回答by Tun Zarni Kyaw

You can change the existing uniqememarray like this

您可以uniqemem像这样更改现有数组

for(int i=0;i<uniquemem.length;i++)
{
    uniquemem[i] = "cn=" + uniquemem[i];
}
attributeSet.add(new LDAPAttribute("uniqueMember", uniquemem));