CSC 102 Lecture Notes Week 6
GUIs (Graphical User Interfaces) using the Processing IDE
Linked Lists and Abstract Data Types
import java.util.*; /**** * * This is a very simple example of a 5-element list of integers, declared as * both an ArrayList and a LinkedList. The interesting thing is the picture of * how memory looks inside the data abstractions: * <p> * <img src = "ArrayAndLinkedListPictures.jpg"> * <p> * This example uses a couple handy utility methods that convert between lists * and arrays -- <tt>asList</tt> and <tt>toArray</tt>. These are defined in * the class java.util.Arrays. Check out its javadoc <a href= * http://java.sun.com/javase/6/docs/api/java/util/Arrays.html> here </a>. * */ public class ArrayListAndLinkedListExample { public static void main(String[] args) { /* Declare and initialize the ArrayList. */ ArrayList<Integer> al = new ArrayList<Integer>(Arrays.asList(10,20,30,40.50)); /* Declare and initialize the LinkedList. */ LinkedList<Integer> ll = new LinkedList<Integer>(Arrays.asList(10,20,30,40.50)); /* Show that the lists are equal as arrays. */ System.out.println(Arrays.equals(al.toArray(), ll.toArray())); } }
Operation | ArrayList | LinkedList | Discussion |
random access | O(1) | O(n) | Random access into an array is O(1) because an array is structured like underlying computer memory for which random access is inherently efficient. In contrast, random access to a linked list is O(n) because you always need to find the nth element by starting at the beginning of the list and counting up to the nth element, which on average takes O(n) time. |
find next | O(1) | O(1) | Finding the next element is O(1) for both types of list. For an array, it's just random access to the i+1 when you're at the ith element. For the linked list, next is a matter of following just one next reference |
add/remove | O(n) | O(1) | Adding and removing are O(n) for an array because the both involve moving blocks of elements to make room for an added element or removing an existing element, which on average takes O(n) time. For a linked list, adding and removing are O(1) since they only involve changing a fixed number of node references. |
forall i, suchthat i >= 0 and i < list.size - 1list[i] < list[i+1]
/**** * A quick example of search for the element of an array. */ public class BasicLinearArraySearch { /** * Search an int array for a particular number. Return the first index * of the number if it's found, -1 if not found. */ public static int searchArray(int a[], int n) { for (int i=0; i<a.length; i++) { if (a[i] == n) return i; } return -1; } /** * Search for a number that's found and another that's not found. */ public static void main(String[] args) { int a[] = {10, 20, 30, 40, 50}; System.out.println("searchArray(a, 40) = " + searchArray(a, 40)); System.out.println("searchArray(a, 45) = " + searchArray(a, 45)); } }