简体   繁体   English

java强制转换ArrayList <StringBuilder> 到ArrayList <String>

[英]java cast ArrayList<StringBuilder> to ArrayList<String>

I'm writing a method in java which requires ArrayList<String> as its output. 我正在用java写一个方法,它需要ArrayList<String>作为其输出。 In this method, String concatenation is frequently used. 在此方法中,经常使用字符串连接。 I use StringBuilder instead of String since String is more expensive in concatenation. 我使用StringBuilder而不是String,因为String在连接中更昂贵。

Before returning result, how could I cast all elements in ArrayList<StringBuilder> to ArrayList<String> ? 返回结果之前,如何将ArrayList<StringBuilder>所有元素转换为ArrayList<String>

how could I cast all elements in ArrayList<StringBuilder> to ArrayList<String> ? 我如何将ArrayList<StringBuilder>所有元素转换为ArrayList<String>

You can't and you shouldn't. 你不能,你不应该。 Make it an ArrayList of one or the other. 使它成为另一个的ArrayList。

Or if you must translate, then you'll need a for loop to iterate through the collection, building the new collection. 或者,如果您必须翻译,那么您将需要一个for循环来遍历集合,从而构建新的集合。

or I suppose you could declare the variable as an ArrayList<? extends CharSequence> 或者我想您可以将变量声明为ArrayList<? extends CharSequence> ArrayList<? extends CharSequence> -- nope that wouldn't work as we're nixed since we can't add(...) anything into a covariant structure, so we wouldn't be able to add anything to this list, just read from it. ArrayList<? extends CharSequence> -不,因为我们无法add(...)任何东西add(...)到协变结构中,所以它不起作用,所以我们不能将任何东西添加到此列表中,只需从它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM