首页 > 解决方案 > Converting LinkedHashSet to ArrayList or just using ArrayList

问题描述

Consider the following code:

final Set<String> allPaths = new HashSet<String>();
for (final String path: paths) {
        allPaths.add(path);
}
final MyData d = new MyData(new ArrayList<String>(allPaths));

MyData is some class I should not touch. It should get an ArrayList as an argument. Before this day, we used that way because we didn't care about the order, that is why we used Set (so there will not be duplicated). But now, I would like to keep the order of the elements, so after some research, I found out that I can use the data structure LinkedHashSet in order to do so. So I did:

final LinkedHashSet<String> allPaths = new LinkedHashSet<String>();
for (final String path: paths) {
        allPaths .add(path);
}
final MyData d = new MyData(new ArrayList<String>(allPaths));

Problem is, I'm not sure how to convert LinkedHashSet to ArrayList. Also, I thought of using ArrayList instead of LinkedHashSet so I won't have to convert it, but I'll have to iterate over the array (O(n)).

What good, clean and effiect way should I use?

标签: javaarraylistlinkedhashset

解决方案


只需使用该public boolean addAll(Collection<? extends E> c)方法,在 arrayList 上,它接受任何Collection.

你有你的LinkedHashSet

final LinkedHashSet<String> allPaths = new LinkedHashSet<String>();
for (final String path: paths) {
        allPaths .add(path);
}

然后执行(即使mylist不为空,您也可以使用它):

List<String> myList = new ArrayList<>();
mylist.addAll(allPaths);

或者更简单的方法:

List<String> myList = new ArrayList<>(allPaths);

推荐阅读