转换 ArrayList到字符串[]
1)我想知道为什么我不能这样做:
ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String[] myentries = (String[])entries.toArray();
这有什么问题吗? (您可能会忽略第二行代码,它与问题无关)
2)我知道使用此代码可以达到我的目标:
ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String[] myentries = new String[entries.size()];
myentries = entries.toArray(myentries)
这是将 ArrayList 转换为字符串数组的首选方式吗?有更好/更短的方法吗?
非常感谢 :-)
1) I am wondering why I can't do this:
ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String[] myentries = (String[])entries.toArray();
What's wrong with that? (You might ignore the second code line, it's not relevant for the question)
2) I know my goal can be reached using this code:
ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String[] myentries = new String[entries.size()];
myentries = entries.toArray(myentries)
Is this the prefered way of converting the ArrayList to a String Array? Is there a better / shorter way?
Thank you very much :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一个示例返回一个
Object[]
因为列表不知道您想要什么类型的数组,并且不能将其转换为String[]
您可以制作第二个一个稍微短一些
The first example returns an
Object[]
as the list doesn't know what type of array you want and this cannot be cast to aString[]
You can make the second one slightly shorter with
ArrayList 创建的支持数组不是字符串数组,而是对象数组,这就是您无法转换它的原因。
关于情况 2。这是将其转换为数组的常见方法,但您可以通过编写以下内容来使其不那么冗长:
The backing array created by the ArrayList isn't a String array, it's an Object array, and that's why you can't cast it.
Regarding case 2. That's the common way to convert it to an array, but you can make it a bit less verbose by writing:
条目的类型丢失(因为 Java 中的泛型被删除)。因此,当您执行 toArray 调用时,它只能返回 Object 类型,因为它知道 List 必须包含对象。所以你可以取回一个包含字符串的 Object[] 。如果您想要一个字符串数组,那么您需要将其传递到 toArray 方法中。通过强制转换,您无法缩小数组引用范围,即无法将对象数组强制转换为字符串数组。但你也可以采取相反的方式,因为它们是协变的。
The type of entries is lost (as Generics are erased in Java). So when you do the toArray call it can only return the Object type back, as it knows the List must contain Objects. So you can get back an Object[] with your Strings in it. If you want to have an array of Strings then you need to pass that into the toArray method. With casting you can't narrow the Array reference i.e. you can't cast an array of Objects into an array of Strings. But you could go the opposite way, as they are covariant.