简体   繁体   English

ArrayList<string> 到字符序列[]</string>

[英]ArrayList<String> to CharSequence[]

What would be the easiest way to make a CharSequence[] out of ArrayList<String> ?ArrayList<String>制作CharSequence[]的最简单方法是什么?

Sure I could iterate through every ArrayList item and copy to CharSequence array, but maybe there is better/faster way?当然我可以遍历每个ArrayList项目并复制到CharSequence数组,但也许有更好/更快的方法?

You can use List#toArray(T[]) for this.您可以为此使用List#toArray(T[])

CharSequence[] cs = list.toArray(new CharSequence[list.size()]);

Here's a little demo:这是一个小演示:

List<String> list = Arrays.asList("foo", "bar", "waa");
CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
System.out.println(Arrays.toString(cs)); // [foo, bar, waa]

Given that type String already implements CharSequence , this conversion is as simple as asking the list to copy itself into a fresh array, which won't actually copy any of the underlying character data.鉴于String类型已经实现了CharSequence ,这种转换就像要求列表将自身复制到一个新数组中一样简单,该数组实际上不会复制任何底层字符数据。 You're just copying references to String instances around:您只是在复制对String实例的引用:

final CharSequence[] chars = list.toArray(new CharSequence[list.size()]);

I know this post is 12 years old but I could not find a solution for this in Kotlin.我知道这篇文章已有 12 年历史,但我在 Kotlin 中找不到解决方案。 Eventually I figured it out:最终我想通了:

Kotlin: Kotlin:

val listOfStrings: List<String> = listOf("Hello,", "World!")
val charSequenceArray: Array<CharSequence> = listOfStrings.toArray(arrayOf<CharSequence>()) //Equivalent type to `CharSequence[]`

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

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