简体   繁体   English

使用相同的顺序java复制arraylist的元素

[英]copy elements of arraylist in a set with the same order java

I've sorted an arraylist of int in ascending order, but when I copy it in a set, the elements are not sorted anymore. 我按升序对int的arraylist进行了排序,但是当我将它复制到一个集合中时,元素就不再排序了。 I'm using this : 我正在使用这个:

HashSet<Integer> set = new HashSet<Integer>(sortedArray);  

why is like that? 为什么会那样?

LinkedHashSet will keep the order. LinkedHashSet将保留订单。 TreeSet will sort based either on an external Comparator or natural ordering through Comparable . TreeSet将根据外部Comparator排序,或者通过Comparable自然排序。

A general point of a Set is that order is irrelevant. Set一般要点是订单无关紧要。 Hashing is intended to put the elements in as random an order as possible. 散列旨在将元素尽可能随机地放入。 LinkedHashSet maintains a linked-list between references to the elements, so can maintain an order. LinkedHashSet维护对元素的引用之间的链接列表,因此可以维护订单。

BitSet (which is not a Set ) may, or may not, provide a more efficient data structure. BitSet (不是Set )可以提供或不提供更有效的数据结构。

HashSet's don't sort or maintain order, and the API will tell you this: HashSet不排序或维护顺序,API会告诉你:

it does not guarantee that the order will remain constant over time. 它不保证订单会随着时间的推移保持不变。

Consider using another type of Set such as a TreeSet. 考虑使用其他类型的Set,例如TreeSet。

If you just care about uniqueness, use the HashSet. 如果您只关心唯一性,请使用HashSet。 If you're after sorting, then consider the TreeSet. 如果您在排序后,请考虑TreeSet。

you need to use TreeSet and implement a Comparator object or Comparable interface for your data. 您需要使用TreeSet并为您的数据实现Comparator对象或Comparable接口。 you can read about Object ordering here hash set is designed for quick access to unique data, not for maintaining a particular order. 你可以阅读这里的对象排序哈希集是为了快速访问唯一数据而设计的,而不是为了维护特定的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM