530 likes | 702 Vues
Objects for Organizing Data --. As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use arrays of objects parameters and arrays multidimensional arrays the ArrayList class additional techniques for managing strings.
E N D
Objects for Organizing Data -- • As our programs get more sophisticated, we need assistance organizing large amounts of data. : • array declaration and use • arrays of objects • parameters and arrays • multidimensional arrays • the ArrayListclass • additional techniques for managing strings
0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 Arrays • An array is an ordered list of values each of which has their own position within the array. • Each value/variable has a numeric index or subscriptto refer to a particular element in the array.
Arrays • For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]);
0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 Arrays • An array of size N is indexed from zero to N-1 • The following array of integers has a size of 10 and is indexed from 0 to 9
ARRAYS • When an array is declared, the name of the array is the address in memory of the first value in the array. For instance, an array of 9 integers (indexed 0-8) would be located in memory like this: View of Memory scores 01 2 3 4 5 6 7 8 1 Location 23 90 40 60 70 75 80 90
Arrays • An array stores multiple values of the same data type. • So if an array of integers is declared, only integers may be stored in that array, no strings or characters.
ARRAY TYPES • The type can be primitive types or objects. • Primitive types include arrays of integers, doubles, chars, longints etc. • Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc.
Arrays • In Java, the array itself is an object. Therefore: • Any of the methods that can be used on an object can be used on an array.
Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • Note that the type of the array (int[]) does not specify its size, • but the new operator reserves memory locations to store 10 integers indexed from 0 to 9.
Arrays • The type of the variable scores is int[] (an array of integers) • It is set to a newly instantiated array of 10 integers. Only integers may be stored in this array. • If we declared an array of strings, only strings may be stored in that array.
Declaring Arrays • Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; int[] intArray ; //allocates no memory
Arrays You cannot access an index of an array until it is instantiated. int[] grades;;// grades Array has no memory allotted grades[3] = 7;// ERROR - grades[3] does not yet exist
Creates AND PRINTS an array with 10 elements class Basic_Array { final static int LIMIT = 10; public static void main (String args[]) { int[] list = new int [LIMIT]; for(int index = 0; index < LIMIT; index++) list[index] = index * 10; list[5] = 999; for (int value : list) // forEach value in list System.out.print (value + " "); } // method main // stores increments of 10 in each element
LIST 01 2 3 4 5 6 7 89 0 10 20 30 40 50 60 70 80 90 01 2 3 4 5 6 7 89 0 10 20 30 40 999 60 70 80 90 Element index 5 is change to 999, which is the 6th element in the array.
Arrays • The constant LIMIT holds the size of the array. This is a good programming technique because it allows you to change the size of the array in one place - at the beginning of the program. • The square brackets in the array declaration are an operator in Java. They have a precedence relative to other operators i.e. the highest precedence. • Both constants in the previous example were declared static because only copy of the size of the array is needed.
Bounds Checking • Each array object has a public constant called length that stores the size of the array. • It is referenced through the array name (just like any other object):
Length of an Array scores.length; • Length is a constant defined in the array class. • scores. length holds the number of elements YOU allocated, not the largest index.
ARRAYS • Arrays are considered to be a static structure because they have a fixed size. • They cannot shrink or grow in size.
Initializer Lists • An initializer list can be used to instantiate and initialize an array in one step. • The values are delimited by braces and separated by commas. Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letter_grades = {'A', 'B', 'C',’D’}; • The letter_grades array consists of an array of 4 characters.
Initializer Lists • Note that when an initializer list is used: • the new operator is not used • no size value is specified • The size of the array is determined by the number of items in the initializer list. • The array size is set to the number of elements in the initializer list.
Outline Declaring and Using Arrays Arrays of Objects Two-Dimensional Arrays Variable Length Parameter Lists The ArrayList Class
Multidimensional Arrays • A one-dimensional array stores a simple list of values. • A two-dimensional array can be thought of as a table of values, with rows and columns. • A two-dimensional array element is referenced using two index values.
two-dimensional array • To be precise, a two-dimensional array in Java is an array of arrays, • therefore each row can have a different length.
one dimension two dimensions Two-Dimensional Arrays • A one-dimensional array stores a list of elements • A two-dimensional array can be thought of as a table of elements, with rows and columns
Two-Dimensional Arrays • A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; • A array element is referenced using two index values: value = scores[3][6] • The array stored in one row can be specified using one index E.G. • scores[2] is row 2
Multidimensional Arrays int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; • The first values - 28, 84, 47 and 72 represent the first row of the array. The second set of values are the 2nd row: 28 84 4772 69 26 91 40 28 42 34 37 13 26 5 35
Two Dimensional Arrays • In an initializer list, the first values represent the first element in the array. {28, 84, 47, 72} • int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; • {28, 84, 47, 72}, is row one
public class PassArrays { public static void main(String args[]) { int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88, 99 } }; printStudentScores( grades[1] ); } // To print one row of the TwoD array public static void printStudentScores( int[] row ) { System.out.print("Scores for student: "); for (int i = 0; i < row.length; i++)System.out.println(row[i]); }
Variable Length Parameter Lists • Suppose we wanted to create a method that processes a different amount of data from one method call to the next • For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);
Variable Length Parameter Lists • We could define two versions of the average method • Downside: we'd need a separate version of the method for each parameter count • We could define the method to accept an array of integers • Downside: we'd have to create the array and store the integers prior to calling the method each time • Instead, Java provides a convenient way to create variable length parameter lists
Indicates a variable length parameter list element type array name Variable Length Parameter Lists • Using special syntax in the parameter list, we define a method to accept any number of parameters of the same type • For each call, the parameters are automatically put into an array for easy processing in the method public double average (int ... list) { // whatever }
Variable Length Parameter Lists public double average (int ... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (intnum : list)// For Each Loop sum += num; result = (double)num / list.length; } return result; } // We need to use the for each loop
Variable Length Parameter Lists • The type of the parameter can be any primitive or object type. • We can send any number of grades to the method below: public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); } grades is the array, Grade is the type
Variable Length Parameter Lists • A method that accepts a variable number of parameters can also accept other parameters • The following method accepts an int, a String object, and a variablenumber of double values into an array called nums public void test (int count, String name, double ... nums) { // whatever } The variable list parameter must be on the end of the parameter list.
The ArrayList Class • An object of class ArrayList is similar to an array in that it stores multiple values • However, a ArrayList • only stores objects. • can grow and shrink in size • Service methods provided by the ArrayList class are used to interact with a ArrayList..
The ArrayList Class • ArrayList is dynamic, that is, it is able to change its’ size as needed . • A static structure like an array has a fixed size throughout its existence. • Each ArrayList initially has a certain amount of memory space reserved for storing elements.
ArrayList Class • If an element is added that doesn't fit in the existing space, more room is automatically acquired. If more room is needed, a new, larger array is allocated and the old array is copied to it We will use this class later.
The ArrayList Class • Elements can be inserted or removed by calling a method in the classs • When an element is inserted, the other elements "move aside" to make room • Likewise, when an element is removed, the list "collapses" to close the gap
ArrayLists • The major advantage of an ArrayList is: • we can store different types of objects in it. • The methods are designed to accept references to any type, • so you can send a reference to a string, an integer, a double etc. can be passed.
Primitive data types & Arraylist • HOWEVER, • If you send a primitive data type, you must first change it to an object. • E.g. You want to send the number 5 • You create an Integer object first: • Integer obj = new Integer(5); • Double doublenum = new Double(2.98);
ArrayList Class • The benefit of storing objects are that • different kinds of objects can be stored in the same data structure. Integers, Doubles, Floats • You must inport the java.util package to use an ArrayList
The ArrayList class Service methods: add(Object element); adds element to end of list remove (Object element); removes the object from the ArrayList. The parameter is an alias to the object to be removed. contains (Object element);returns true if the object is in the ArrayList. get (int index)returns the object at the index specified. ensureCapacity()expands array by creating a new array and copying old one to the new one lastIndexOf(Object element)returns the last occurrence of element. size()returns the number of objects. … and many more
The ArrayList Class • An ArrayList stores references related to the Object class, • So you can store any kind of object • We can also define an ArrayListto accept a particular type of object
The following declaration creates an ArrayList object that only stores Family objects, not allowing other types of objects to included ArrayList<Family> reunion = new ArrayList<Family> • This is an example of generics introduced a few years ago . • It is also the reason why I cannot get my DatingService applet to run on the browsers
Static variables • Suppose we have a law firm that wants to keep count of the number of new clients added each. • We would implement a Client class and put a counter in it so we could access anytime. • The Client class has a getter method called • Return count()
public class Client implements Comparable<Client>{ private intcount = 0;private String lastname, firstname, …… • // constructor increments count when client created public Client(String lastname, String firstname, ….) {this.lastname = lastname;this.firstname = firstname; count++;} public intreturnCount() { return count; } …. Other code
Using static variables • So we create a large number of clients during the day and then want to know the count. • We create the last client of the day: • Client c1 = new Client(“Harry”, “Hamlin” ….etc) • And call the returncount method to find our total • client count • int count = c1.return count(); • WHAT VALUE IS returned and stored in count?
Static variables • One - yes - one! -because count is an instance variable in the Client class and each new client gets its own copy. • It is only incremented once – when the client is created. • When the next client is created, it had its own copy and it is only incremented once. • LET MAKE COUNT STATIC!
public class Client implements Comparable<Client>{ private static intcount = 0; private String lastname, firstname, …… • // constructor increments count when client created public Client(String lastname, String firstname, ….) {this.lastname = lastname;this.firstname = firstname; count++; } public intreturnCount() { return count; } …. Other code