将 StringBuilder 内容“传输”到 Java 中的新 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12814112/
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
'transferring' StringBuilder contents to a new ArrayList in java
提问by OcelotXL
If I have two class constants:
如果我有两个类常量:
List<String> workingList= new ArrayList<String>();
StringBuilder holder = new StringBuilder(50);
both residing within, call it class StringParser
and primary method readStuff()
...
两者都驻留在其中,称之为类StringParser
和主要方法readStuff()
......
public class StringParser{
public void readStuff(){
//parsing logic and adding <String> elements to
//said workingList...
}//end of method readStuff
followed by a method where I inspect the contents of workingList
...
其次是一种方法,我检查workingList
...的内容
public String someReaderMethod()
{
int ind = 0;
for(int i = 0; i < workingList.size();i++)
{
if(workingList.get(i).contains(someExp))
{
workingList.remove(ind);
holder.append(workingList.get(i).toString());
}
else
{
++ind;
}
}
return holder.toString();
}
}
...given that StringBuilder
holder now contains what workingList
has removed, is there a way I can 'pass' the contents of StringBuilder
to a new ArrayList
?
...鉴于该StringBuilder
持有人现在包含workingList
已删除的内容,有没有办法可以将 的内容“传递”StringBuilder
给新的ArrayList
?
采纳答案by aradhak
Is there a reason why u want to use a StringBuilder? You can directly insert the values into a new ArrayList. I think you could do it in a simpler way.
你有什么理由想要使用 StringBuilder 吗?您可以直接将值插入到新的 ArrayList 中。我认为你可以用更简单的方式做到这一点。
List<String> discardedList = new ArrayList<String>();
public void readStuff() {}
public static List<String> someReaderMethod()
{
for(int i = 0; i < workingList.size(); i++)
{
if(workingList.get(i).contains(someExp))
{
discardedList.add(workingList.get(i));
workingList.remove(i);
}
}
return discardedList;
}
回答by Amit Deshpande
You will need a deliminator
to parse string and then you can use Split
method and convert String[] to ArrayList.
您将需要一个deliminator
来解析字符串,然后您可以使用Split
方法并将 String[] 转换为 ArrayList。
holder.append(tempList.get(i));
holder.append(";");//Deliminator
Now when you have to use it you need to do
现在当你必须使用它时,你需要做
String[] strings =holderString.split(";");
List<String> list = Arrays.asList(strings);
回答by Rohit Jain
While appending your List elements to your StringBuilder
object, you need to append an extra delimiter after every append..
在将 List 元素附加到StringBuilder
对象时,您需要在每次附加后附加一个额外的分隔符。
Later on, you can split the String
in StringBuilder
on that delimiter, and then convert your String array thus obtained to an ArrayList
..
稍后,您可以在该分隔符上拆分String
in StringBuilder
,然后将由此获得的 String 数组转换为ArrayList
..