Element[] array = {new Element(1),new Element(2),new Element(3)};
The simplest answer is to do:
Element[] array = new Element[] { new Element(1),new Element(2),new Element(3) };
List<Element> list = Arrays.asList(array);
This will work fine. But some caveats:
- The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new ArrayList(). Otherwise you'll get an UnsupportedOperationException.
- The list returned from asList is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.
List<Element> arraylist = new ArrayList<Element>(Arrays.asList(array));
本文详细介绍了如何使用Arrays.asList()将元素数组转换为List,并阐述了固定大小的List带来的限制和潜在问题。建议在需要动态添加或删除元素时,使用ArrayList包裹List来避免UnsupportedOperationException。
784

被折叠的 条评论
为什么被折叠?



