ArraysUsing arraysCreating ArraysArrays & LoopsArray ExamplesArray Example (another)Java Basics – ArraysSlide 8Slide 9ArrayListArrayList (cont)Convenient to use ArrayList , not arrayExample: singleNumbersFirst convert array to ArrayListSecond, find unique numbersThird, convert ArrayList to ArrayCompSci 69.1ArraysAggregate data typeDeal with items of same typeLists of wordsNumbers AnalogiesMailboxes in post officeCD racks with slotsSimplifies namingWhat if you needed to come up with unique name for each data item?Allows use of loopsRequired for many mathematical and statistical problemsMultiple elements or cellsCompSci 69.2Using arraysUse subscript or index to access an elementx[5] = 20;System.out.println("Result is " + x[5]);First element is element 0, not 1!!!Often used in loopsint k = 0, sum = 0; while ( k < 10 ) { sum = sum + measurements[k]; k = k + 1; } Note that subscript is an int variable, kCompSci 69.3Declarationdouble weights[];Definitionweights = new double[50];Combine declaration and definitiondouble weights[] = new double[50];int num[] = new int[6];num[1] = 21; num[5] = 13;Creating Arrays? ? ? ? ? ?? 21 ? ? ? 13CompSci 69.4Arrays & Loopsnum[0] = 0;int k = 2;while(k < num.length){ num[k] = k * k; k = k + 1;} Subscript range errors! ! !Java checks (many languages do not)Costs & tradeoffs0 21 4 9 16 25CompSci 69.5Array ExamplesSum up elements in a list (4 ways to do same thing) Count occurrences of somethingSearch for somethingInformation retrievalint k = 0, sum = 0;while (k < 10) { sum = sum + data[k]; k = k + 1;}int k = 1, sum = 0;while (k <= 10) { sum = sum + data[k – 1]; k = k + 1;}int k = 9, sum = 0;while (k >= 0) { sum = sum + data[k]; k = k - 1;}int k = 10, sum = 0;while (k > 0) { k = k - 1; sum = sum + data[k];}CompSci 69.6Array Example (another)Example: method to count number of A grades public static int getAs(int[] grades) { int aCount = 0; for (int k = 0; k < grades.length; k++){ if (grades[k] >= 90) aCount++; } return aCount; }Understand each line …CompSci 69.7Java Basics – ArraysArray BoundsIndex must in range 0 <= k < grades.lengthElse get ArrayIndexOutOfBoundsExceptionShort Circuit EvaluationAllows expression of the formif (k>=0 && k<grades.length && grades[k] >= 90) { aCount++; }Safe from exceptionOrder important!Holds for any chain of ANDed termsSimilar rules for chain of ORed termsCompSci 69.8Java Basics – ArraysCreating Arrays (by example)int[] counts = new int[101];String[] colors = new String[3];Counter[] tallies = new Counter[10];int[] codes;codes = new int[17];Using Initializer ListsString[] colors = {”red”, ”green”, ”blue”}; double[] shims = {1.0, 1.1, 1.3, 1.6, 1.9, 2.5};Initializing Object ArraysFor most object arrays, need to create objects in the arrayfor (int k = 0; k < tallies.length; k++){ tallies[k] = new Counter();}CompSci 69.9Java Basics – ArraysArrays are ObjectsBehavior of arrays similar to other objectsThus grades.length worksAssignments (Warning!)Since array identifiers are just referencesoArray assignment doesn’t create new array!Use newArrayname = arrayname.clone();oThis works well for arrays of primitivesWhat happens for arrays of objects?CompSci 69.10ArrayListBetter to use than an array (very often)ArrayListCan grow and shrinkHas methods for common tasks (see API)Only holds objectsCan’t have an ArrayList of int or doubleThere is a special Integer (an int that is an object) and Double (note the capital letters!) classCompSci 69.11ArrayList (cont)Create an ArrayList ArrayList<Integer> idlist = new ArrayList<Intger>();Add an element to the ArrayList idlist.add(8);Modify kth element in an ArrayList idlist.set(k,9);Sum the elements in the ArrayList // sum up integers in the ArrayList int sum = 0; for (Integer current : idlist) { sum += current; }CompSci 69.12Convenient to use ArrayList , not arrayIf you are given an array as a parameterCopy values to an ArrayListThen can work with the ArrayListIf you need to return an arrayCopy values from ArrayList to an arrayFor Example, you’ll need to do both of these for APTs that use arrays.CompSci 69.13Example: singleNumbersGiven an integer array that could have duplicates, return an array that has only unique numbers from the original arrayFor example if the parameter array is:8 5 5 8 5Then the array to return should be:8 5CompSci 69.14First convert array to ArrayListpublic int[] singleNumbers(int[] ids){ // convert the array ids into an ArrayList idlist ArrayList<Integer> idlist = new ArrayList<Intger>(); for (int k = 0; k < ids.length; k++) { idlist.add(ids[k]); }Alternatively, loop can be written as for (int id : ids) { idlist.add(id); }CompSci 69.15Second, find unique numbers// create an ArrayList that will hold unique numbersArrayList<Integer> singles = new ArrayList<Integer>();singles.add(idlist.get(0)); // first number is uniquefor (Integer current : idlist) { boolean isIn = false; for (Integer currentSingle : singles) { if (current.equals(currentSingle)) isIn = true; } if (!isIn) singles.add(current);}CompSci 69.16Third, convert ArrayList to Array// convert ArrayList to arrayint[] answer = new int[singles.size()];int position = 0;for (Integer currentSingle : singles) { answer[position] = currentSingle; position++;}return
View Full Document