1 / 85

Objects for Organizing Data --

Objects for Organizing Data --. As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array declaration and use arrays of objects parameters and arrays multidimensional arrays the ArrayList class

Download Presentation

Objects for Organizing Data --

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Objects for Organizing Data -- • As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: • array declaration and use • arrays of objects • parameters and arrays • multidimensional arrays • the ArrayListclass • additional techniques for managing strings

  2. Static Variables - Details • Normally, each object has its own data space. • If a variable is declared as static, only one copy of the variable exists for all objects of the class private static int count; • Changing the value of a static variable in one object changes it for all others. • Static variables are sometimes called class variables.

  3. The static Modifier • Unless otherwise specified, a member declared within a class is an instance variable. In the following Numbers class, there are • Two instance variables, • an integer - num1 • an integer - count • plus one accessor method - ReturnNum().

  4. Class Numbers • In this version , there are two instance variables. class Number { private int count = 0 ; private int num1; public Number(int value) { // constructor num1 = value; count ++; } public int returnNum() { // service method return num1; }

  5. Static Variables • Each object that it is created in the Numbers class contains a: • copy of the num1 and count variables • and has access to the ReturnNum method. • Each object has unique values for the num1 instance variable and count.

  6. Class Numbers In the main method of the Driver class, class Test class Test { public static void main(String args[]) { Number num1 = new Number(17); Number num2 = new Number(12); } In memory, number has a copy of num1 and count Number 58 Number 2 60 58 num1 17 count 1 60 num2 12 count 1

  7. Static Variables • When declaring a static variable or method, only one copy of the variable or method is created. All instances of the class share the same copy. class Number { static int count = 0; // one copy for all instances private int num1; public Number(int value) { count++; num1 = value ; } public int returnNum() { return num1; } }

  8. Class Numbers num1 57 num2 60 57 num1 17 60 num1 20 62 count 2 class Test { public static void main(String args[]) { Number num1 = new Number(17); Numbernum2= new Number(20); } In memory, number1 and Number2, and two copies of num1 are stored but there is one copy of count for the class

  9. Static Variables • Memory space for a static variable is created when the class is first referenced • All objects instantiated from the class share its static variables • Changing the value of a static variable in one object changes it for all others

  10. Static Variables • When used properly, static variables are very effective. • There is only one copy of the static variables named in a class. • This means that all the objects created from that class do not receive a copy of the static variables. • They just have access to their value

  11. Class Student class Student { private static int count = 0; // a static variable private int SocSecNum; private String name; public Student () { //CONSTRUCTOR count = count + 1; } // constructor Student public int ReturnCount() { return count; } // method ReturnCount

  12. Instance Variable and Methods • Every time you instantiate a new object from a class, you get a new copy of each of the class’s instance variables. • With every new Student object, you get a new name variable associated with the new Student object. • All instances of the same class share the same implementation of the ReturnCount method. • Objects outside the Student class can only access the static variable count through the ReturnCount method.

  13. The static Modifier • Thestatic modifier can be applied to variables or methods. • It associates a variable or method with the class rather than an object. • This approach is a distinct departure from the normal way of thinking about objects. • We have already seen the static modifier used with variables. It can also be used with methods.

  14. Static Methods • Static methods are invoked using the class name and are sometimes called class methods. • Sometimes it is convenient to have methods that can be used without creating an object. • For instance, every time you want to use the factorial method or the method that we used to uppercase a character you don’t want to create an instance of the class.

  15. The static Modifier • So, you create static methods. To invoke these methods, you simply use the class name, where you would otherwise use the object name. E.g.; • For example, the Math class and the Character classes in the java.lang.package contains several static method operations: Math.abs (num)// absolute value Character.toUppercase (c)// uppercases a char y = Math.sqrt.(x) • We used the methods in the character class without instantiating an instance of the class.

  16. Static Methods • Normally, we invoke a method through an instance (an object) of a class. • If a method is declared as static, it can be invoked through the class name; no object needs to exist.

  17. Static Methods class Helper { public static int cube (int num) { return num * num * num; } } Because it is declared as static, the method can be invoked as value = Helper.cube(5);

  18. Static Class Members • Static methods and static variables often work together • The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method • See SloganCounter.java (page 294) • See Slogan.java (page 295)

  19. Arrays 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 • An array is an ordered list of values each of which has their own position within the array. • It is a collection of variables that share the same name. • Each value/variable has a numeric index or subscript to refer to a particular element in the array.

  20. 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]);

  21. Arrays 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 • 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

  22. Arrays • A particular value is referenced using the array name followed by the index in brackets For example, the expression: scores[4]; refers to the value 67 (which is the 5th value in the array). Scores[0]is first element in the array - all indexes start at 0. The value stored in the 3rd index is the 4th element. • Scores[4] is a place to store a single integer, and can be used wherever an integer variable can. For example, it can be assigned a value, printed, used in a calculation.

  23. 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) called intArray would be located in memory like this: View of Memory scores 1 Location 23 90 40 60 70 75 80 90 01 2 3 4 5 6 7 8

  24. 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. • 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.

  25. 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. • The name of the array is a reference variable, and the array itself is instantiated separately.

  26. Arrays • The chess object Bishop points to the place in memory where all the variables and methods associated with the Bishop object are located, • So the name of the array points to the place in memory where the individual values of the array are stored.

  27. Declaring Arrays • Since arrays are objects, the reference must first be declared and then the array can be instantiated. • 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.

  28. Arrays • The type of the variable scores is int[] (an array ofintegers) • 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.

  29. 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

  30. 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

  31. Creates an array with 10 elements class Basic_Array { final static int LIMIT = 10; // value will not change as final static int INCREMENT = 10; // only one copy needed public static void main (String args[]){ int[]list = new int[LIMIT]; for(int index = 0; index < LIMIT; index++) list[index] = index * INCREMENT; list[5] = 999; for (int value : list) // forEach value in list System.out.print (value + " ");} // method main // stores increments of 10 in each element

  32. 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.

  33. 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.

  34. Bounds Checking problem • If the array codes can hold 100 values, it can only be indexed using the numbers 0 to 99 • If count has the value 100, then the following reference will cause an ArrayOutOfBoundsException: System.out.println (codes[count]); • It’s common to introduce off-by-one errors when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;

  35. Bounds Checking • Once an array is created, it has a fixed size. An index used in an array reference must specify a valid element. • That is, they must be in bounds (0 to N-1). • The Java interpreter will throw an exception if an array index is out of bounds. So that in our list array of 10 elements, if you tried to access: list[11] an exception called ArrayIndexOutofBoundsException would result. The java index operator performs automatic bounds checking.

  36. 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):

  37. Length of an Array scores.length; • Length is a constant defined in the array class. • scores. length holds the number of elements allocated, not the largest index. • That is, it holds the number of items you allocated for the array when you declared it.. • In the program Reverse_Numbers, an array is constructed to store numbers which are printed out in reverse.

  38. ARRAYS • Arrays are considered to be a static structure because they have a fixed size. They cannot shrink or grow in size. • Data structures like arrays are good when we know ahead of time how many elements are needed. • Other data structures like ArrayLists and linked lists can be used when it is necessary to dynamically build a structure to hold elements. • This is necessary when the number of elements is not known ahead of time.

  39. Array Declarations Revisited • The brackets of the array type can be associated with the element type or with the name of the array.Therefore float[] prices; and float prices[]; are essentially equivalent. The first format is usually more readable as most variables are declared as: int sum, total, num // which is closer to int[] sum, total, num // versus int sum[], total, num // which is confusing

  40. 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 array units is instantiated as an array of 10 ints, indexed from 0 to 9. • The letter_grades array consists of an array of 4 characters.

  41. Initializer Lists • Note that when an initializer list is used: • the new operator is not used • no size value is specified • the type of each value in the list must be the same as the data type of the array. • The size of the array is determined by the number of items in the initializer list. An initializer list can only be used in the declaration of an array. • The array size is set to the number of elements in the initializer list.

  42. INITIALIZING ARRAYS • When an array object is instantiated, the elements in the array are initialized to the default value of the indicated data type. • That is, it you declare an array of integers, each element is initialized to 0. • However, it is always better to do your own initialization.

  43. Array Examples int Numbers[] = new int[100] Numbers[0] = 0; for(int i = 1; i < Numbers.length; i++) Numbers[i] = i + Numbers(i-1]; • We used the lengthfield, which is the field provided in the array class to contain the length of the array. This field is read-only. • Though arrays are objects and can access all the methods that objects can, the syntax associated with them is somewhat different from that of other objects.

  44. class Evens { final int SIZE = 10; public static void main(String[] args ) { int [] intArray = new int [SIZE]; for (j = 0; j < SIZE ; j++)intArray[j] = 2 + 2 * j; System.out.println(“ Element Value “); for (j = 0; j <= SIZE -1; j++) System.out.println(“ “ + j + “ “ intArray[j]); } // method main } class evens

  45. CLASS SUM class Sum {public static void main(String[] args ) { int [] intArray = { 1, 3, 5, 4, 7, 2, 16, 99, 45, 67 }; int total = 0; // accumulate the total of the elements in the arrayfor (int j = 0; j < intArray.length; j++) total = total + intArray[j]; // print results System.out.println(“ Total array elements is “, total); } // method main } // class Sum output : Total of array elements is 287

  46. Command-Line Arguments • The main method has a parameter that it takes an array of String objects as a parameter • These values come from command-line arguments that are provided when the interpreter is invoked • For example, the following invocation of the interpreter passes three String objects into main: > java StateEval pennsylvania texas arizona • These strings are stored at indexes 0-2 of the array parameter of the main method • See NameTag.java (page 393)

  47. Examples of Arrays class Echo { public static void main(String[] args ) { for (int j = 0; j < args.length; j++) System.out.print( arg[j] + “ “); System.out.println (“ “); } // method main } // class Echo output: prints out the contents of String[] args which is the values the user specified: java Echo Mary Sam Bill prints Mary Sam Bill

  48. ArrayCopy • It is possible to copy one array to another array with the arraycopy method: public static void arraycopy(Object sourceArray, int srcIndex, Object destination, int destIndex, int length). • The two objects are the source and destination arrays, the srcIndex and destIndex are the starting points in the source and destination arrays, and length is the number of elements to copy. E.g.:

  49. Copying Arrays public static void main(String args[]){char[] copyFrom = { ‘d’,’e’,’c’,’a’, ‘f’, ‘f’,’e’,’i’ ‘n’};char[] copyTo = new char[7];System.arraycopy(copyFrom, 2, copyTo, 0,7); } • Arraycopy method begins the copy at element number 2 in the source array (copyFrom) which is element ‘c’. It copies it to the destination array (copyTO) starting at index 0. It copies 7 elements, ‘c’ to ‘n’ into copyTO. 2 d e c a f f e i n copyFrom 0 1 2 3 4 5 6 c a f f e i n copyTO

  50. Arrays of Objects • Objects can have arrays as instance variables. Therefore, fairly complex structures can be created simply with arrays and objects • The software designer must carefully determine an organization for each application.

More Related