CS 211: ArrayList
Transcription
CS 211: ArrayList
CS 211: ArrayList Chris Kauffman Week 10-1 Front Matter Goals Today I Feedback I ArrayList Lab 10: Exercises P4: Panic! Due Sunday 3/29 at 11:59pm I Questions? Midterm Feedback I Have a look at results I Posted to piazza later today Overall Messages 1. Lab Task/Quiz time constraints are hard I I Future Task/Quiz will be shorter Need "better" prep exercises 2. More overview of exercises in lab I Will instruct lab leaders 3. Folks don’t collaborate on lab exercise I Why not? 4. Awesome Stuff I I I I Folks are starting projects reasonably early BJP is best textbook we’ve found for CS 211 so far P3 Target difficulty was right on Automatic/Manual Grading System Schedule: 1 week behind posted 3/30 4/6 4/13 4/20 4/27 5/4 Week 10 Week 11 Week 12 Week 13 Week 14 Makeups ArrayList and Generics Recursion Review and Exam 2 Linear and Binary Search Comparable/Comparator and Collections Stacks/Queues, Review ArrayList Crash Course Weird new syntax with angle braces. ArrayList<String> as = new ArrayList<String>(); as.add("Hi"); as.add("Bye"); System.out.println(as.get(1)); Have a look at UseArrayList.java ArrayList Goodies JavaDoc for ArrayList a.get(5) a.set(5, x) a.add(x) a.add(i,x) int n = a.size(); a.indexOf(x) access assignment append, grow if needed insert, shift/grow as needed how many elements linear search Big win in ArrayList over standard arrays: they grow as needed I How could that work? You should want to know. . . Preview: Collections ArrayList is a collection I Part of Java’s collections framework I Implements Collection<E> JavaDoc for Collection interface All Collections. . . JavaDoc for Collections class A lot of static methods that do stuff to classes implementing Collection sort binarySeach max/min swap addAll These all look weird, mention a Comparator a lot I We’ll get to that later Warning: No Primitives Allowed Can’t do ArrayList<int> a = ... No primitives allowed; will discuss this shortly Instead do ArrayList<Integer> a = ... Boxed and Unboxed | Unboxed | Boxed | | Primitive | Reference | |-----------+-----------| | int | Integer | | double | Double | | char | Character | | float | Float | | boolean | Boolean | Compiler is smart about converting between these two Exercise: Naive Median Calculation Median Age I File stores name/age pairs I Compute the median of the ages I Median is the middle score of the sorted ages Advice I Use ArrayList to make input easy I Use a Collections method to make sorting easy I Use appropriate ArrayList methods to access elements I Use Integer rather than int names-ages.txt Demo Run Dexter Debra Angelos Vincent Maria James Brian Harrison Rita Cody Lila > javac ComputeMedian. > java ComputeMedian n Sorted ages: 0: 1 1: 9 2: 28 3: 29 4: 30 5: 32 6: 35 7: 37 8: 39 9: 39 10: 43 median: 32 35 32 43 30 39 39 37 1 29 9 28