Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use which Data Structure? [closed]

I am studying Data Structures in a Fundamentals of Software Development course. I have encountered the following data structures:

  • Structs
  • Arrays
  • Lists
  • Queues
  • Hash Tables

... among others. I have a good understanding of how they work, but I'm struggling to understand when and where to use them.

I can identify the use of the Queue Data structure, as this would be helpful in printer and/or thread queuing and prioritizing.

Knowing the strengths and weaknesses of a data structure and implementing it in code are different things, and I am finding the former difficult.

What is a simple example of the use of each of the data structures listed above?

For example:

Queue: first-in, first-out → used for printer queue to queue docs

like image 332
Vincent Vega Avatar asked Sep 14 '25 03:09

Vincent Vega


1 Answers

I had trouble understanding them when i first started programming and so i decided to give a heads up to start with.

I am trying to be as simple as possible. Try Oracle Docs fro further details


Struct: When ever you need Object like structure, where you can group related data, use structs. Structs are very rarely used in java though(as objects are created in their place)

Arrays: Arrays are contiguous memory. when ever you want fixed time access based on index, unlike linkedlist, arrays are very fast and so use them.

But the backlog with arrays is that you need to know the size at the time of initialization. Also arrays does not support higher level methods such as add(), remove(), clear(),contains(), indexOf() etc.


List: is an interface which can be implemented using Arrays(ArrayList) or LinkedLists (LinkedList). They support all the higher level methods specified earlier.

Also Lists re-sizes themselves whenever it is getting out of space. You can specify the initial size which the underlying Arrays or LinkedLists will be created, but whenever the limit is reached, it created the underlying structure with a bigger size and then copies the contents of the initial one.


Queue or Stack: is an implementation technique and not really a data structure. If you want FIFO implementation, you implement Queue on either Arrays or LinkedList(yes, you can implement this technique on both these data structures) https://en.wikibooks.org/wiki/Data_Structures/Stacks_and_Queues


HashMap: Hashmap is used whenever you want to store key value pairs. if you notice, you cannot use arrays or linked lists or any other mentioned data structure for this purpose. a key can be any thing from String to Object(but note that it has to be an object and cannot be a primitive) and a value can also be any object


google out each data structure for more details

like image 101
prasad vsv Avatar answered Sep 16 '25 17:09

prasad vsv