我需要使用可以 -
的数据结构下面是我使用LinkedList的代码,但它没有过滤掉任何重复项。它有removeFirst()
方法来获取和删除列表中的第一个元素。
public static LinkedList<String> getData(TypeEnum types) {
LinkedList<String> listOfPaths = new LinkedList<String>();
String prefix = types.equals(TypeEnum.PARTIAL) ? TypeEnum.PARTIAL.value() : TypeEnum.UNPARTIAL.value();
listOfPaths.add(prefix + LOCAL_PATH); // first element in the list is always LOCAL PATH
for (String path : REMOTE_PATH) {
listOfPaths.add(prefix + path);
}
return listOfPaths;
}
以下是我使用getData
方法的方法:
LinkedList<String> data = getData(types);
String local_path = data.removeFirst(); // this is my local path
// use local_path here
// now iterate all the remote path
for(String remotePath : data) {
// do something with remotePath
}
我在这里有哪些选择才有效率?是否有任何其他数据结构可以通过避免重复来做同样的事情。我知道Set可以做到这一点,但是Set没有任何removeFirst
方法,也不确定它是否是一个在这里使用的正确结构。此外,任何人都可以提供一个例子。
答案 0 :(得分:4)
您可以使用LinkedHashSet(维护广告订单)。例如,首先将项目添加到此Set
以过滤掉重复项,然后将所有项目添加到LinkedList
:
public static LinkedList<String> getData(TypeEnum types) {
LinkedList<String> listOfPaths = new LinkedList<String>();
LinkedHashSet<String> uniques = new LinkedHashSet<String>();
String prefix = types.equals(TypeEnum.PARTIAL) ? TypeEnum.PARTIAL.value() : TypeEnum.UNPARTIAL.value();
uniques.add(prefix + LOCAL_PATH); // first element in the list is always LOCAL PATH
for (String path : REMOTE_PATH) {
uniques.add(prefix + path);
}
listOfPaths.addAll(uniques);
return listOfPaths;
}
答案 1 :(得分:0)
这个答案是根据@copeg评论修复的,谢谢。
解决方案可能只是通过执行以下操作来扩展list add方法:
public class MyList<E> extends LinkedList<E> {
@Override
public boolean add(int index, E element){
if(this.contains(element))return false;
return super.add(index,element);
}
}