Download presentation
Presentation is loading. Please wait.
1
Lecture 6 Objects for Organizing Data
Instructors: Fu-Chiung Cheng (鄭福炯) Associate Professor Computer Science & Engineering Tatung Institute of Technology 1 1
2
Outline array declaration and use arrays of objects
parameters and arrays multidimensional arrays the Vector class additional techniques for managing strings 1 1
3
Arrays An array is an ordered list of values
Each value has a numeric index 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 scores 2
4
Arrays Array reference: scores[4] the 5th value in the array
refers to the value 67 It can be assigned a value, printed, used in a calculation 3
5
Arrays An array stores multiple values of the same type
That type can be primitive types or objects We can create an array of integers, or an array of characters, or an array of String objects, etc. Array is an object The name of the array is a object reference variable, and the array itself is instantiated separately 4
6
Declaring Arrays The scores array could be declared as follows:
int[] scores = new int[10]; Type: int[] (an array of integers) Size: 10 (array of 10 integers) Unknown size: a handle to an array object int[] scores; 5
7
Declaring Arrays Some examples of array declarations:
float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; 6
8
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 This is called automatic bounds checking Its common to inadvertently introduce off-by-one errors when using arrays 7
9
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): scores.length Note that length holds the number of elements, not the largest index See Reverse_Numbers.java and Adjust_Test_Scores.java 8
10
Array Declarations Revisited
Array declarations: two ways float[] prices; and float prices[]; are essentially equivalent The first format is usually more readable 9
11
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: char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; int[] primes = {2, 3, 5, 7, 11, 13, 17, 19}; 10
12
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 An initializer list can only be used in the declaration of an array 11
13
Arrays of Objects The elements of an array can be object references
The declaration String[] words = new String[25]; reserves space to store 25 references to String objects It does NOT create the String objects themselves Each object stored in an array must be instantiated separately 12
14
Arrays of Objects Objects can have arrays as instance variables
Fairly complex structures can be created simply with arrays and objects See RollCall.java (next 4 pages) 13
15
class RollCall { public static void main (String[] args) { Membership roster = new Membership(); Member person; System.out.println(); person = roster.findMember(26911); if (person == null) System.out.println ("No match found"); else { System.out.println (”Found the following member:"); person.print(); } roster.print(); } // method main } // class RollCall
16
class Membership { private Member[] memberList; public Membership() { memberList = new Member[4]; memberList[0] = new Member ("Johnny Storm", 70469); memberList[1] = new Member ("Sue Richards", 69048); memberList[2] = new Member ("Reed Richards", 26911); memberList[3] = new Member ("Ben Grimm", 89696); } // constructor Membership public Member findMember (int target) { int index = 0; while (index < memberList.length) { if (memberList[index].getMembershipNumber() == target) return memberList[index]; index++; } return null;
17
public Member findMember (int target) {
int index = 0; while (index < memberList.length) { if (memberList[index].getMembershipNumber() == target) return memberList[index]; index++; } return null; } // method findMember public void print() { System.out.println ("Member\t\tId #"); for (int person=0; person < memberList.length; person++) memberList[person].print(); } // method print } // class Membership
18
class Member { private String name; private int membershipNumber; public Member (String memberName, int idNumber) { name = memberName; membershipNumber = idNumber; } // constructor Member public int getMembershipNumber() { return membershipNumber; } // method getMembershipNumber public void print() { System.out.println (name + "\t" + membershipNumber); } // method print } // class Member
19
Arrays as Parameters An entire array can be passed to a method as a parameter The reference to the array is passed, making the formal and actual parameters aliases of each other Changing an array element in the method changes the original An array element can be passed to a method as well, and follow the parameter passing rules of that element's type See Array_Test.java 14
20
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 A two-dimensional array in Java is an array of arrays, therefore each row can have a different length 15
21
Multidimensional Arrays
An initializer list can be used to create and set up a multidimensional array Note that each array dimension has its own length constant See MultiArrayTest.java (Next page) See Class MultiArray 16
22
class MultiArrayTest {
public static void main (String[] args) { MultiArray chart = new MultiArray(); chart.print(); System.out.println(); for (int column=0; column < 4; column++) System.out.println ("Sum of column " + column + ": " + chart.sumColumn (column)); } // method main } // class MultiArrayTest
23
class MultiArray { int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; public void print() { for (int row=0; row < table.length; row++) { for (int column=0; column < table[row].length; column++) System.out.print (table[row][column] + " "); System.out.println(); } } // method print public int sumColumn (int column) { int sum = 0; for (int row=0; row < table.length; row++) if (column < table[row].length) sum += table[row][column]; return sum; } // method sumColumn } // class MultiArray
24
What is wrong with this class?
class Soda_Scores { private final int RESPONDENTS = 10; private final int SODAS = 4; private int[][] results = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, {3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} }; public int num_sodas() { return SODAS; } public boolean worthy (int soda, int level) { int count = 0; for (int person=0; person < results[soda].length; person++) if (results[soda][person] >= level) count++; return (count > RESPONDENTS/2); } // method worthy } // class Soda_Scores What is wrong with this class?
25
The Vector Class An object of class Vector is similar to an array in that it stores multiple values However, a vector only stores objects does not have the indexing syntax that arrays have Service methods are used to interact with a vector The Vector class is part of the java.util package See Beatles.java (next page)
26
import java.util.Vector;
class Beatles { public static void main (String[] args) { Vector band = new Vector(); band.addElement ("Paul"); band.addElement ("Pete"); band.addElement ("John"); band.addElement ("George"); System.out.println (band); band.removeElement ("Pete"); band.addElement ("Ringo"); } // method main } // class Beatles
27
The Vector Class An important difference between an array and a vector is that a vector can change its size as needed. Each vector initially has a certain amount of memory space reserved for storing elements If an element is added that doesn't fit in the existing space, more room is automatically acquired
28
The Vector Class A vector is implemented using an array
Whenever new space is required, a new, larger array is created, and the values are copied from the original to the new array To insert an element, existing elements are first copied, one by one, to another position in the array Therefore, the implementation of Vector in the API is not very efficient See ZZ_Top.java (Next) 19
29
import java.util.Vector; // page 825
class ZZ_Top { public static void main (String[] args) { Vector song = new Vector(); String name = new String ("ZZ Top's Greatest Hits"); Integer track = new Integer (6); String title = "Cheap Sunglasses"; Double price = new Double (15.95); Vector authors = new Vector (2); authors.addElement ("Gibbons"); authors.addElement ("Hill"); song.addElement (track); song.addElement (title); song.addElement (authors); song.addElement (price); song.insertElementAt (name, 0);
30
System.out.println (song);
authors.addElement ("George"); System.out.println ("song size: " + song.size()); System.out.println ("authors size: " + authors.size()); System.out.println ("song begins: " + song.firstElement()); System.out.println ("authors begins: " + authors.firstElement()); System.out.println ("song ends: " + song.lastElement()); System.out.println ("authors ends: " + authors.lastElement()); authors.setElementAt ("Frank", authors.indexOf ("George")); song.removeAllElements(); } // method main } // class ZZ_Top
31
The StringTokenizer Class Revisited
We've seen a StringTokenizer object separate a string into separate tokens By default, those tokens are delimited by white space By using other StringTokenizer constructors, we can define the delimiters used to define a token We can also set whether we want the delimiters themselves returned as tokens See Voltaire.java and URL_Tokens.java
32
import java.util.StringTokenizer; // page 805
public class Voltaire { public static void main (String[] args) { String quote = "Use, do not abuse; neither abstinence " + "nor excess renders a man happy."; StringTokenizer words = new StringTokenizer (quote); System.out.println ("Characters: " + quote.length()); System.out.println ("Tokens: " + words.countTokens()); while (words.hasMoreTokens()) { System.out.println (words.nextToken()); } } // method main } // class Voltaire
33
class URL_Tokenizer { private String protocol; private String address; private String resource; public URL_Tokenizer (String URL_Text) { StringTokenizer URL = new StringTokenizer (URL_Text, ":"); protocol = URL.nextToken(); address = URL.nextToken (":/"); resource = URL.nextToken (""); } // constructor URL_Tokenizer public String get_protocol() { return protocol; } public String get_address() { return address; } public String get_resource() { return resource; } } // class URL_Tokenizer … URL_Tokenizer url = new URL_Tokenizer (" // main
34
The StringBuffer Class
Recall that the value of a String object is immutable; once set it cannot be changed The StringBuffer class can be used to define a character string whose value can change It's service methods include the ability to append and insert characters See Money.java However, most functionality defined by the StringBuffer class can be accomplished with String objects and string concatenation
35
public class Money { public static void main (String[] args) { StringBuffer text1 = new StringBuffer(); // page 803 StringBuffer text2 = new StringBuffer(" m"); StringBuffer text3 = new StringBuffer ("1 dollar"); text1.append (1); text1.append (" p"); text1.append ('e'); text1.append ('n'); text1.append ("ny"); text2.insert (0, 1); text2.insert (2, "di"); text2.insert (5, 'e'); System.out.println (text1); System.out.println (text2); System.out.println (text3); text3.reverse(); } // method main} // class Money
36
Conclusion Java Array is an object. Array size of N: index 0 to N-1
Bounds checking Mutlidimensional array ==> array of arrays each element could have a different length. Vector (similar to Array) can dynamically change size StringTokenizer class (good for compiler and other app. StringBuffer class
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.