Here is the sample code to go with the question. This API is trying to implement a graph with an adjacency-list representation as an array of Bags indexed by each of vertices in the graph.
public class Graph{
private final int V; //no. of vertices
private Bag<Integer>[] adj; // A bag for each vertex to store all adjacent vertices
.
.
.
}
Is there any advantage of using a Bag here over a linked list or a Set. I know that bags are unordered but why go with an unordered list when they don't save us time or space?
A Bag is likely implemented with a binary search tree or hash table, giving us O(log n) or O(1) searches. A linked list is going to give O(n) searches.
A Set only allows unique elements, so if you need to store duplicates you need a Bag. The TreeSet or HashSet in the Java Collections library will give us O(log n) or O(1) searches, respectively.
In general, the Set or Bag interfaces will be more suitable when you often need to perform search or delete operations. If you just need to add to the end of the collection and iterate over it, there wouldn't be much difference.