Topic 09: Data Structures


Published on


Published in: Education
  • Be the first to comment

  • Be the first to like this

Topic 09: Data Structures

  1. 1. Topic 9 : Data Structures DDOOCP
  2. 2. Learning Objectives › Understand the advantages of the ArrayList class. › Program ArrayList objects. › Understand the advantages of the LinkedList class. › Program LinkedList object.
  3. 3. ArrayList › The ArrayList class is used to create an array that can change its size at runtime or gives you a dynamic array. › It implements the List interface to provide the dynamic behavior to the array. › Constructor – ArrayList( )
  4. 4. ArrayList › Methods – boolean add(Object o) – void add(int index, Object o) – void clear( ) – boolean isEmpty( ) – Object remove(int index) – int size( ) – Object get(int index)
  5. 5. ArrayList Example
  6. 6. LinkedList › Arrays and ArrayLists are not very efficient with the processes of insertion and deletion of elements as it involves much moving of data. › As a result, the data structure of a LinkedList was introduced. › A LinkedList is a collection of boxes organised in a list, where every box has a pointer which points to the next box in the list and another pointer which points to the previous box in the list. › The boxes can be anywhere in RAM, unlike arrays which have to use contiguous memory locations. › There is no concept of an array involved. The list is managed entirely by the pointers.
  7. 7. LinkedList › However, there are also disadvantages: 1. The management process takes more memory than the management of an array. 2. Access to a particular element is slow compared with the direct access that arrays offer via the index structure.
  8. 8. Important Questions › Explain the benefits of using a LinkedList over an ArrayList and give an example of when you would use a LinkedList in preference to an ArrayList. › Explain the benefits of using an ArrayList over a LinkedList, and give an example of when you would use an ArrayList in preference to a LinkedList › One of the limitations of a standard array is that its length is fixed. State a data structure that can be used to give the benefits of an array without this limitation, and provide a code example in which an array and your suggested data structure perform the same duty.
  9. 9. Important Questions › Provide a comparison of arrays and ArrayLists, giving an example of when each might be preferred over the other. › Provide the code to create an ArrayList of Strings, add three string variables to the ArrayList, and then loop over the ArrayList to print out the contents. › Describe a Java data structure that can represent a real world table of data.