在Java中将列表转换为数组[重复]

本文探讨如何在Java中将ArrayList转换为String数组。提到常见的做法是利用构造函数创建新数组,并提供了一种在Java 8中的替代方案。
摘要由CSDN通过智能技术生成

本文翻译自:Convert list to array in Java [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

How can I convert a List to an Array in Java? 如何在Java中将List转换为Array

Check the code below: 检查以下代码:

ArrayList<Tienda> tiendas;
List<Tienda> tiendasList; 
tiendas = new ArrayList<Tienda>();

Resources res = this.getBaseContext().getResources();
XMLParser saxparser =  new XMLParser(marca,res);

tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();

this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);  

I need to populate the array tiendas with the values of tiendasList . 我需要填充阵列tiendas用的值tiendasList


#1楼

参考:https://stackoom.com/question/eAJv/在Java中将列表转换为数组-重复


#2楼

Try this: 试试这个:

List list = new ArrayList();
list.add("Apple");
list.add("Banana");

Object[] ol = list.toArray();

#3楼

tiendas = new ArrayList<Tienda>(tiendasList);

All collection implementations have an overloaded constructor that takes another collection (with the template <T> matching). 所有集合实现都有一个重载的构造函数,它接受另一个集合(模板<T>匹配)。 The new instance is instantiated with the passed collection. 使用传递的集合实例化新实例。


#4楼

我认为这是最简单的方法:

Foo[] array = list.toArray(new Foo[0]);

#5楼

This (Ondrej's answer): 这(Ondrej的回答):

Foo[] array = list.toArray(new Foo[0]);

Is the most common idiom I see. 这是我看到的最常见的习语。 Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. 那些建议你使用实际列表大小而不是“0”的人误解了这里发生的事情。 The toArray call does not care about the size or contents of the given array - it only needs its type. toArray调用不关心给定数组的大小或内容 - 它只需要它的类型。 It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. 如果采用实际类型会更好,在这种情况下,“Foo.class”会更加清晰。 Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. 是的,这个成语生成一个虚拟对象,但包含列表大小只是意味着你生成一个更大的虚拟对象。 Again, the object is not used in any way; 同样,该对象不以任何方式使用; it's only the type that's needed. 它只是需要的类型。


#6楼

Java 8中的替代方案:

String[] strings = list.stream().toArray(String[]::new);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值