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
String array : Adding elements in Loop
提问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 StringBuffer
in forloop to add/append content dynamically but it is accepting only String[].
Please help me solve this issue
我曾尝试通过使用List<String>
和StringBuffer
forloop 动态添加/追加内容,但它只接受 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 uniqemem
array like this
您可以uniqemem
像这样更改现有数组
for(int i=0;i<uniquemem.length;i++)
{
uniquemem[i] = "cn=" + uniquemem[i];
}
attributeSet.add(new LDAPAttribute("uniqueMember", uniquemem));