Arrays, ArrayLists, and Collections. Rationale Suppose we have a program to compute the average of...
-
Upload
sarah-sullivan -
Category
Documents
-
view
216 -
download
0
Transcript of Arrays, ArrayLists, and Collections. Rationale Suppose we have a program to compute the average of...
Arrays, ArrayLists, and Collections
Rationale
• Suppose we have a program to compute the average of three numbers.
• We could write a simple little method to compute the average given the three numbers passed in.
/** * Suppose we want to compute the average of a set of numbers. We might be able to justify not * using arrays when we only need to compute the average for a couple of values, but when the * number of values we need to compute the average for gets larger the harder it is to compute * work with individual variables for each....hence the need for arrays. **/public class RationaleForArrays{ /** * Where we could do this for simple cases like computing the average for three numbers. **/ public double computeAverage(double n0, double n1, double n2) { return (n0 + n1 + n2)/3.0; } public static void main(String argv[]) { RationaleForArrays rationale = new RationaleForArrays(); /* * Although we could justify explicitly individual values when we are * dealing with a small number of variables... */ double number0 = 0.00 * 1.001; double number1 = 1.00 * 1.001; double number2 = 2.00 * 1.001; System.out.printf("Average for %3d numbers : %8.4f -- without array\n", 3, rationale.computeAverage(number0, number1, number2)); }}
OUTPUT:Average for 3 numbers : 1.0010 -- without array
What if it was more than 3 numbers …
• What if it was 100 numbers …
• or a 1,000 or 10,000 or even a million..
• What if you did not know the number of numbers you need to compute the average of when you were writing your routine?
• We need the ability to get/set a list of these numbers … sounding like arrays
Java Arrays
• Arrays are a structured way to store multiple homogenous data in a single variable
• Index through the array starting with 0 to length-1• If you try to access outside the array’s valid range
you get an ArrayIndexOutOfBoundsException• Must be declared up front with some predetermined
size and type• Can be single or multidimensional
– single dimensional are a series of values (think of a column of values)
– multiple dimensional are implemented as an array of arrays (think of rows of columns)
• Can store primitives or object type data
Working with Arrays
• Declaring// single dimensionaldouble score[]; // same as double[] score;
• Declaring and Creating an Arraydouble score[] = new double[100];double matrix[][] = new double[10][10];
• Declaring and Initializing an Arraydouble score[] = { 98.0, 87.5, 100.0 };double matrix[][] = { { 10.0, 20.0 }, { 30.0, 40.0 },};
Some Examples of Arrays
public void examplesOfArrays() { double score[] = { 98.0, 87.5, 100.0 }; double matrix[][] = { { 10.0, 20.0 }, { 30.0, 40.0 }, }; System.out.println("\nSingle dimenstional array of scores:"); for(int i = 0; i < score.length; ++i) System.out.printf("Score %2d = %4.2f\n", i, score[i]); System.out.println("\n\nMatrix:"); for(int row = 0; row < matrix.length; ++row) { for(int col = 0; col < matrix[0].length; ++col) { System.out.printf(" %4.2f", matrix[row][col]); } System.out.println(); } } OUTPUT:
Single dimensional array of scores:Score 0 = 98.00Score 1 = 87.50Score 2 = 100.00
Matrix: 10.00 20.00 30.00 40.00
So lets go back and look at that computing the average now with arrays …
/** * Suppose we want to compute the average of a set of numbers. We might be able to justify not * using arrays when we only need to compute the average for a couple of values, but when the * number of values we need to compute the average for gets larger the harder it is to compute * work with individual variables for each....hence the need for arrays. **/public class RationaleForArrays{ /** * As the number of values increase or non-deterministic at compile time. **/ public double computeAverage(double number[]) { double sum = 0.0; for(int i = 0; i < number.length; ++i) sum += number[i]; return sum/number.length; } public static void main(String argv[]) { RationaleForArrays rationale = new RationaleForArrays(); double number[] = null; number = new double[3]; for(int i = 0; i < 3; ++i) number[i] = i * 1.001; System.out.printf("Average for %3d numbers : %8.4f -- with array\n", number.length, rationale.computeAverage(number)); number = new double[100]; for(int i = 0; i < 100; ++i) number[i] = i * 1.001; System.out.printf("Average for %3d numbers : %8.4f -- with array\n", number.length, rationale.computeAverage(number)); /* * Did you notice that the code did not change when we changed * from 3 numbers to 100..... :-) */ }}
OUTPUT:
Average for 3 numbers : 1.0010 -- with arrayAverage for 100 numbers : 49.5495 -- with array
What else should we know about arrays? public void moreExamplesOfArrays() { String sa1[] = { "zero", "one", "two", "three", "four", "five" }; String sa2[] = { "0", "1", "2", "3", "4", "5" }; String sa3[] = { "d", "b", "f", "a", “c" }; /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sa1.length; ++i) System.out.printf("\t%s", sa1[i]); System.out.println(); /* copying array elements * System.arraycopy(src, srcPos, dest, destPos, length) */ System.arraycopy(sa2, 0, sa1, 0, 2); System.out.printf("After the copy \n"); for(int i = 0; i < sa1.length; ++i) System.out.printf("\t%s", sa1[i]); System.out.println(); /* sorting array elements */ System.out.printf("Before the sort \n"); for(int i = 0; i < sa3.length; ++i) System.out.printf("\t%s", sa3[i]); System.out.println(); Arrays.sort(sa3); System.out.printf("After the sort \n"); for(int i = 0; i < sa3.length; ++i) System.out.printf("\t%s", sa3[i]); System.out.println(); }
OUTPUT: from arraycopy(…)Original Strings zero one two three four five
After the copy 0 1 two three four five
This is the same as setting the values individually in the code.Hence, we get no performance enhancement for doing this, just convince.
OUTPUT: from Arrays.sort(…)Before the sort d b f a cAfter the sort a b c d f
Given what we know now … Can you think of how we could implement dynamic arrays?
Instead of us having to doing worrying about dynamically resizing, we can use an ArrayList
ArrayList
• Comparing ArrayList to Java arrays:– similar:
• a sequence of objects• each object is index from 0 to size -1
– different:• only can contain objects (no primitives)• size() instead of length• array[i] = value array.set(i, value)• can grow and shrink in size
Important ArrayList Methods
• Constructors– ArrayList(Collection)– ArrayList(initialSize)
• Methods– add(index, object)add an element to the list at a given location– add(object) add a given element to the list– addAll(Collection) add all the elements to the list– clear() remove all the elements– get(index) get the object at a specified index– remove(index) remove the element at a specified index– set(index, object) set a given object at a given index– size() number of elements in the list– toArray() convert to an array– trimToSize() trim to the current size
ArrayList Examples
public void examplesOfArrayList() { ArrayList<String> sal1 = new ArrayList<String>(3); sal1.add("d"); sal1.add("b"); sal1.add("a");
/* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();} OUTPUT:
Original Strings d b a
ArrayList is a Collection
• As a result the Collections utility class can be used to help out.– binary search for an element– copy a list to another list– enumerate over a collection– fill a list with a given object– reverse– rotate– shuffle– sort– swap to elements in a list
Collections Examples public void examplesOfArrayList() { ArrayList<String> sal1 = new ArrayList<String>(3); sal1.add("d"); sal1.add("b"); sal1.add("a"); /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();
Collections.sort(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the sort\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.reverse(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the reverse\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); }
OUTPUT: Original Strings d b a
After the sort a b d
After the reverse d b a
public void examplesOfArrayList() { ArrayList<String> sal1 = new ArrayList<String>(3); sal1.add("d"); sal1.add("b"); sal1.add("a"); /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();
Collections.sort(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the sort\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();
Collections.reverse(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the reverse\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();
Collections.rotate(sal1, 1); /* use of Collections utility */ System.out.printf("\n\nAfter the rotate\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();
Collections.shuffle(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the shuffle\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println();
Collections.shuffle(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the shuffle\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); }
OUTPUT: Original Strings d b a
After the sort a b d
After the reverse d b a
After the rotate a d b
After the shuffle b d a
After the shuffle a d b
The Collections Framework
• Collection Interfaces– Set
• A collection of not duplicating elements• Only contains methods exposed in Collection but adds uniqueness to the elements.• Implementations: HashSet, TreeSet, LinkedHashSet
– List• A collection of elements (can contain duplicates)• Additions to Collection: positional access, search, iteration, range view• Implementations: Vector (retrofitted), ArrayList, LinkedList
– Queue• A collection of elements that follow a FIFO pattern• Implementations: LinkedList, PriorityQueue
– Map• A collection of name-value pairs.• Names can not be duplicated.• Implementations: HashMap, TreeMap, LinkedHashMap
• Object Ordering– SortedSet – Iterator & toArray return the elements in “sorted” order– SortedMap - Iterator & toArray return keys, values, or entries in “sorted” order
The Collections Framework
Hash
Table
Resizable
Array
Balanced
Tree
Linked
List
Hash Table
+
Linked List
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Map HashMap TreeMap LinkedHashMap