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?
Each data structure can be used under different circumstances:
Set
(specifically HashSet
) can be list of unordered unique elements. On the other hand, Bags
are multisets (unordered collections that may contain duplicate elements).
As for LinkedList
they provide easier link manipulation i.e. adding elements at different places, is much easier (constant time).