Unformatted text preview:

CompSci 611.1More Arraysÿ The Partially Filled Array Often create array large enough to handle worst case That means, in practice, array is seldom fully utilized Need extra variable to keep track of used portionÿ (Note that ArrayLists can avoid that problem if used right) Use the proper methods for adding and removing Results in the size() method being correctCompSci 611.2More Arraysÿ Partially Filled Array Example Roster of team: may not be filled (assume a Team class)String[] roster = new String[MAX_TEAM_SIZE];int numMembers = 0;public void addPlayer(String name){roster[numMembers] = name;numMembers++;} What was (carelessly) assumed here?public void printTeam(){for (intk=0;k<numMembers;k++)System.out.println(roster[k]);} Why didn’t we use roster.length here?CompSci 611.3More Arraysÿ Partially Filled Array Example (continued) Removing a team member can be non-trivialpublic void removePlayer(String name){int loc = -1;for (int k = 0; k < numMembers; k++){if (roster[k].equals(name)) {loc = k;break;}}// What if not found: How do we tell?roster[loc] = roster[numMembers]; // what’s this?numMembers--;} What were some of the (dubious??) assumptions here?CompSci 611.4The Arrays Classÿ Collection of methods used with arrays See APIÿ Following very useful static void fill(type arrayName,type value)o Arrays initialized to 0 (or null) on creationo Allows other values or “make sure” static void sort(type arrayName)o Will look at sorting latero State-of-the-art sortso Data must be Comparable static List asList(Type arrayName)o Useful in converting arrays to ArrayLists and other listsCompSci 611.5Computing Frequencypublic class FrequencyCounter {final static int MAX_VALUE = 10;final static int SIZE = MAX_VALUE+1;final static String stars ="*******************************";int[] counters;public FrequencyCounter() {counters = new int[SIZE];Arrays.fill(counters, 0);}public void getFreq(int[] data){for (int k = 0; k < data.length; k++){int n = data[k];counters[n]++;}}CompSci 611.6Computing Frequencypublic void histogram(){for (int k = counters.length -1; k >= 0; k--){int f = counters[k];System.out.println(k + "\t" +stars.substring(0, f));}}public static void main(String[] args) {int[] test = {10, 9, 10, 7, 4, 9, 9, 10, 8, 9,8, 10, 9};FrequencyCounter fc = new


View Full Document

Duke CPS 006 - More Arrays

Download More 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 More 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 More 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?