Introduction to Java Arrays and Array Lists Arrays An array is an indexed list of values Any type int double String boolean All values in an array must have same type Arrays Example int 7 10 1 2 5 6 0 1 2 3 4 n 1 The index starts at zero and ends at length 1 Arrays An array is defined using Type Example int values new int 10 values 0 7 values 1 10 values 9 6 values 10 6 Wrong Arrays You can initialize an array when declaring the array int values 7 10 1 2 5 Access array elements using operator values 3 int x values 5 1 Array Each array has a length int values 7 10 1 2 5 int valuesize values length 5 Array Two Dimensional Arrays int table new int 3 3 int table 1 2 3 6 7 8 4 5 6 Array Lists An array list manages a sequence of objects or values Two conveniences Array lists can grow and shrink dynamically as needed Array lists offer method for many common tasks such as inserting removing elements Array Lists Creates an array list ArrayList grades new ArrayList Integer ArrayList names new ArrayList String ArrayList uscstudents new ArrayList Student Array Lists boolean add Object obj Appends the obj to the end of the list Object remove int index Removes the element at index from the list Object get int index Returns the object at index of the list int size Returns the number of elements in the list Array Lists boolean isEmpty Returns true if the list has no elements void clear Removes all elements of the list boolean add int index Object obj Insert the object into the location of given index Array Lists boolean add Object obj Examples grades add 100 100 grades add 85 100 85 grades add 80 100 85 80 grades add 82 100 85 80 82 Array Lists Object remove int index Examples 100 85 80 82 int pos 2 grades remove pos 100 85 82 100 80 82 Array Lists Determine the number of elements Array String Array List a length a length a size Array Algorithms Counting matches Find a Value Maximum or Minimum Sort elements Inverse the array Array Algorithms Counting Matches Array Algorithms Find a match Array Algorithms Maximum or Minimum Array Algorithms Sort Elements Popular algorithms Insertion sort Selection sort Bubble sort Quick sort Merge sort Checking Problem Write an efficient method to find the maximum nonrepeated grade in an array of grades The grades in array are integers from 0 to 100 For example if the array is 100 90 90 80 100 60 the return value is 80 Checking Problem Algorithm 1 Sort the grades Find the maximum grade appearing once Time Complexity O nlogn O n O nlogn Find an algorithm with a time complexity O n Any Questions
View Full Document
Unlocking...