简体   繁体   中英

Java List and Collection ordering inquiry

I know a List in java is guaranteed to maintain an order, but a Collection is not.

My question is, if I have a list1, and I assign that list1 to a collection, and then I cast that collection to a List list2, will list2 have the same order as list1?

Or can it lose the order since it was at some point habdled as a collection?

Thank you all for your help.

You are mixing up two concepts:

  1. The compile time declaration of a variable, field, ...
  2. The runtime "identity" of an object

In other words; of course, the compiler lets you write:

List<Whatever> stuff = new ArrayList<>();
stuff.add(whatever);

Collection<Whatever> stuffInCollection = stuff;
Object loosingAllTypeInformation =  stuffInCollection;
List<Whatever> castingBack = (List<Whatever>) loosingAllTypeInformation;

But at runtime, none of these assignments have any effect on the list object in memory. It still sits there, it is still an ArrayList object; and it has one member of type Whatever.

In other words: creating multiple variables/fields that reference the same object doesn't have any (direct) effect on the referenced object; no matter what kind of object that is.

The only thing that might change when having multiple variables/field reference the same object might be the point in time when that object is eligible to be garbage collected.

Order will be the unchanged, because you always handled references to the initial List which does not change anything in the List instance.

It is different if you add the List to a Set. This would, dependent on the Set you use, change the order.

更改引用类型不会影响对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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