Unformatted text preview:

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.1ArraysAggregate data typeDeal with items of same typeLists of wordsNumbers AnalogiesMailboxes in post officeCD racks with slotsSimplifies namingWhat if you needed to come up with unique name for each data item?Allows use of loopsRequired for many mathematical and statistical problemsMultiple elements or cellsCompSci 69.2Using arraysUse 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.3Declarationdouble 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 ExamplesSum up elements in a list (4 ways to do same thing) Count occurrences of somethingSearch for somethingInformation 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 – ArraysArray BoundsIndex must in range 0 <= k < grades.lengthElse get ArrayIndexOutOfBoundsExceptionShort Circuit EvaluationAllows expression of the formif (k>=0 && k<grades.length && grades[k] >= 90) { aCount++; }Safe from exceptionOrder important!Holds for any chain of ANDed termsSimilar rules for chain of ORed termsCompSci 69.8Java Basics – ArraysCreating 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 ArraysFor 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 – ArraysArrays are ObjectsBehavior of arrays similar to other objectsThus grades.length worksAssignments (Warning!)Since array identifiers are just referencesoArray assignment doesn’t create new array!Use newArrayname = arrayname.clone();oThis works well for arrays of primitivesWhat happens for arrays of objects?CompSci 69.10ArrayListBetter to use than an array (very often)ArrayListCan grow and shrinkHas methods for common tasks (see API)Only holds objectsCan’t have an ArrayList of int or doubleThere 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 arrayIf you are given an array as a parameterCopy values to an ArrayListThen can work with the ArrayListIf you need to return an arrayCopy values from ArrayList to an arrayFor Example, you’ll need to do both of these for APTs that use arrays.CompSci 69.13Example: singleNumbersGiven an integer array that could have duplicates, return an array that has only unique numbers from the original arrayFor example if the parameter array is:8 5 5 8 5Then 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

Duke CPS 006 - Arrays

Download Arrays
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Arrays and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Arrays 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?