[英]'transferring' StringBuilder contents to a new ArrayList in java
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
?
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);
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
.. 稍后,您可以在该分隔符上的StringBuilder
拆分String
,然后将由此获得的String数组转换为ArrayList
。
Is there a reason why u want to use a StringBuilder? 您是否有理由要使用StringBuilder? You can directly insert the values into a new ArrayList. 您可以将值直接插入到新的ArrayList中。 I think you could do it in a simpler way. 我认为您可以通过更简单的方式来做到这一点。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.