2

Bags are stored in arrays. I do understand that we can change the size of bags as we want etc.. However, since it is stored in array, it basically has an index number isn't it? In this case, why do we still say that it is unordered?

Yuan
  • 65
  • 7

1 Answers1

7

Bags are stored in arrays

No they are not.

Actually, they might be, depending on implementation, but they surely don't have to be. It's like saying a List is stored in an array. That is e.g. true for an ArrayList, but not true for a LinkedList.

So what's the difference between a bag, a list, and a set?

  • A list is ordered, allowing duplicates

    • Generally has slow lookup by value.
    • ArrayList implementation uses array, with fast lookup by position.
    • LinkedList implementation uses doubly-linked nodes, with fast insert/remove at beginning of list.
  • A set is unordered, no duplicates

    • Generally allows fast lookup by value.
    • HashSet implementation is unordered.
    • LinkedHashSet implementation is ordered.
    • TreeSet implementation is sorted.
  • A bag is unordered, allowing duplicates

    • No built-in Java support. Generally just use List if needed.
      Recommend using third-party library if fast lookup by value is needed.

It's the definition of the terms that specifies the ordered vs unordered semantics. An implementation of a bag might happen to keep ordering, but it's not required by the generic term bag.


Let's clear up the confusion about bags in Java.

None of them specifies that a bag is a list, and none of them uses array to implement the bag.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • The first point is key to the difference as Arrays and Bags are children of java.util.List, which I believe Yuan is asking for clarification. It really is just how you implement. Normally bags are found with Hibernate for queries and it is necessary to use implement a strategy. [this has a good explanation from Java.org](https://thoughts-on-java.org/association-mappings-bag-list-set/) – Kevin Aug 29 '19 at 18:18
  • 3
    @Kevin *"Bags are children of java.util.List"* No they are not. The Java Runtime Library doesn't have any `Bag` type. – Andreas Aug 29 '19 at 19:02
  • Whoops! you are right, I'm thinking in the context of PersistentBag which implements List. Thanks for the catch! – Kevin Aug 30 '19 at 18:18