我需要按照传递到集合中的相同顺序恢复java集合集合接口的元素。
在java中这是怎么可能的呢?
发布于 2011-05-17 20:30:55
那LinkedHashSet呢?
哈希表和链表实现的Set接口,具有可预测的迭代顺序。此实现与HashSet的不同之处在于,它维护一个通过其所有条目运行的双向链表。这个链表定义了迭代顺序,这是元素插入到集合中的顺序(插入顺序)。请注意,如果将元素重新插入到集合中,则插入顺序不会受到影响。(如果当s.add(e)在紧接调用之前返回true时调用s.contains(e),则元素e被重新插入到集合s中。)
发布于 2011-05-17 20:31:55
public class SimpleLinkedHashSetExample {
public static void main(String[] args) {
//create object of LinkedHashSet
LinkedHashSet lhashSet = new LinkedHashSet();
/*
Add an Object to LinkedHashSet using
boolean add(Object obj) method of Java LinkedHashSet class.
This method adds an element to LinkedHashSet if it is not
already present in LinkedHashSet.
It returns true if the element was added to LinkedHashSet, false otherwise.
*/
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
/*
Please note that add method accepts Objects. Java Primitive values CAN NOT
be added directly to LinkedHashSet. It must be converted to corrosponding
wrapper class first.
*/
System.out.println("LinkedHashSet contains.." + lhashSet);
}
}
/*
Output of the program would be
LinkedHashSet contains..[1, 2, 3]
*/ 你可以使用上面的例子中的LinkedhashSet。
https://stackoverflow.com/questions/6030780
复制相似问题