Order of elements in a set in java

If I create 2 lists from the same set, can I be sure that I get the same order in both lists? (I'm not interested in ordering if both lists are in the same order, and I don't perform any operations on sets between creating two lists.)

List l = new ArrayList(set);

List l1 = new ArrayList(set);

I understand that there are guaranteed ways to create these lists and get the same order, and that there is no good reason for me to create two lists in this way, but I would like to know why the ordering of elements in set will change if operations are not performed on it changes.

Edit: set is an unordered hashset

+4
source share
5 answers

l l1. , , .

Set, . .

new ArrayList(Collection) toArray, Javadoc Set#toArray():

, . - , , .

Javadoc Set#iterator() , :

. ( - , ).

, .

+5

public ArrayList ( c) , ,

Set, .

, LinkedHashSet, .

+4

, . Set, Java, . , ArrayList Set. , , , , . , Set contains find , .

-, SortedSet, , . Java 6 , SortedSet. TreeSet ConcurrentSkipListSet.

SortedSet LinkedHashSet . , .

0

( ) , Set, - Set ( , a SortedSet) . , , , - , :

// set = ...
List<? extends Comparable> list = new TreeSet<>(set).stream().collect(Collectors.toList());

, . TreeSet. , .

0

, .

List list = new ArrayList(set);

List secondList = new ArrayList(list);
-2

Source: https://habr.com/ru/post/1679480/


All Articles