Presentation is loading. Please wait.

Presentation is loading. Please wait.

Phil Tayco Slide version 1.0 Created Oct 16, 2017

Similar presentations


Presentation on theme: "Phil Tayco Slide version 1.0 Created Oct 16, 2017"— Presentation transcript:

1 Phil Tayco Slide version 1.0 Created Oct 16, 2017
Strings and Arrays Phil Tayco Slide version 1.0 Created Oct 16, 2017

2 Strings Revisited We’re used to thinking of primitive data types as those that are given to us by the compiler such as int and double Memory is automatically allocated and if initialized properly, values are stored as normal Strings get the same treatment String name = “Phil Tayco”; The “name” variable is automatically allocated memory to store a String Initialization follows the same pattern

3 Strings Revisited Behind the scenes, though, a String is treated like a reference! The dynamic memory use is done because String lengths vary (if a String length changes, memory is automatically reallocated accordingly) Strings are treated like normal variables, though, because they are a very popular data type. They get the simple treatment but are technically references like classes Many programming languages like Java support this combination and treat Strings as a class! name 0x1f74ccb0 Phil Tayco

4 String Class A review of the Java API String class shows there are constructors and member functions like all other classes You don’t have to create a String using a constructor, but you can Many languages provide common String functions to parse through String contents (see ch. 16 of the Java book) This is all convenient in Java, but you also have to be careful, particularly when testing 2 Strings for equality…

5 Comparing Strings in Java
String s1 = “Hello”; String s2 = “Hello”; In this example, s1 and s2 are 2 Strings Remember that s1 and s2 are really String objects which means they have their own references to physically separate memory allocations This is important to know because with Strings getting similar treatment as simple data types, equality tests don’t work. Do you see why? s1 0x4412ff20 s2 0x45ca123d Hello Hello

6 Comparing Strings in Java
if (s1 == s2) System.out.println(“They are equal”); s1 and s2 are references. When comparing for equality, the operation compares the contents of s1 and s2 to see if they have the same value In this example, s1 and s2 have 2 different memory addresses. Even though they point to two locations in memory with the same contents, the references are different (s1 == s2) will then return false. How do you compare String contents?

7 A Method to the Madness if (s1.equals(s2))
System.out.println(“They are equal”); The “equals” method takes a String as an input parameter and compares the contents of that String with the String object contents that called the function This will return true and print “They are equals” Would the same result occur if you said (s2.equals(s1)) ? Other programming languages may support a String comparison operation that allow you to say “(s1 == s2)”. Review the language API to see what is appropriate to do for your needs

8 Arrays Revisited Recall how Java arrays are created int[] numbers;
This is a variable declaration of an integer array called numbers When we look under the hood, numbers is also just a reference and in this case, the memory for the array is not yet allocated We have to define how many integers we want to reserve for the array to allocate memory numbers ?

9 Arrays Revisited numbers = new int[10];
This reserves 10 integers in memory In Java, since the type of the array elements is simple, they are initialized with a given value of 0 Notice how the memory allocation is done using the “new” keyword. It’s the same notation as creating an object Arrays are data structures that get a similar class treatment numbers 0x3320aad2 1 2 9

10 Array Length A good example of an Array used like a class is the “.length” property in Java int[] numbers = new int[10]; for (c = 0; c < numbers.length; c++) System.out.println(numbers[c]); .length is a special property for all Arrays that return the capacity of the Array The property is public because it is popular to use. It is also considered to be a fixed value as once you allocate memory for an Array, the size is fixed In this example, numbers.length has a value of 10

11 Fun With Arrays Remember the defining elements of an array:
An ordered set of elements referred to by the same variable name with each element accessed by an index Each element is the same data type The second point is of most significance with classes because remember what a class is: it’s a complex data type! Just like you can create an array of integers, now you can also create an array of Students… Student[] roster = new Student[50]; Arrays of objects need to be treated with care but as seen with other examples, even though the complexity increases, the pattern of use is consistent

12 Arrays Step By Step Student[] roster;
As with an Array with simple data types, the declaration of roster here is only creating the reference with no memory allocated When we are ready to allocate memory for the roster Array, we state the number of Student elements to reserve What will the array elements actually look like? What will the array elements be initialized to? roster ?

13 Arrays Step By Step roster = new Student[50];
This reserves 50 Student references in memory At this point, each Student element has no memory allocated. Only references are created Important distinction to make is that we’ve created memory for the array, but each element does not have an actual Student object yet Any element can have a Student object created at any time but note that also means until that point, the element is pointing to null roster 0x2d2a1100 ? ? ? ? 1 2 49

14 Arrays Step By Step roster[0] = new Student();
Roster[1] = new Student(123, “Phil Tayco”); This creates 2 Student objects in the first 2 elements of the roster array Lots of observations to make with this configuration roster 0x2d2a1100 0x17f32a20 0x44a059f2 ? ? 1 2 49 -1 123 “” “Phil Tayco”

15 Arrays of Objects Once an element of the roster is instantiated, treatment of the object is as normal with the proper Array notation roster[0].setId(456); Array elements are references so you can set one element equal to another (to be used with care!) roster[2] = roster[0]; Array elements are instantiated as normal objects such as using the default constructor or any other overloaded one

16 Arrays of Objects The most common error to make with Arrays of objects is to attempt to use member functions for elements that have not yet been instantiated for(int c = 0; c < roster.length; c++) System.out.println(roster[c].getId()); The problem here is that roster.length returns the capacity of the array and not the actual number of elements that have been instantiated In this example, roster.length is 50. If only 2 objects have been instantiated, the other 48 will have null values Accessing a member function of a null object in Java results in a “NullPointerException”. When using Arrays of Objects, get familiar with this run-time error!

17 Arrays of Objects How best to deal with this is to maintain a numberOfStudents variable that maintains how many Student objects in the roster have been instantiated Student[] roster = new Student[50]; roster[0] = new Student(); roster[1] = new Student(123, “Phil Tayco”); int numberOfStudents = 2; for(int c = 0; c < numberOfStudents; c++) System.out.println(roster[c].getId()); This also means you must maintain numberOfStudents appropriately (instantiations and deletions) as well as the array contents (no “gaps” in the array)

18 Composition with Arrays
The fun doesn’t stop there! Recall the definition of designing classes with Composition – you can have a class with a property that is another class Since Arrays are classes, it is possible to create a property that is an Array public class Gradebook { private int numberOfStudents; private String courseName; private Student[] roster; } This is a powerful class design incorporating all of what we’ve learned that sets up the foundation for advanced OO concepts later on. Understand this structure well!

19 Composition with Arrays
As with other concepts going from simple to complex, maintain the design patterns Start with the constructors. What would the default look like? public Gradebook() { numberOfStudents = 0; courseName = “”; roster = new Student[50]; } numberOfStudents and courseName are simpler design decisions for their default values For the roster array, all we did here is allocate the size of the roster. No elements are instantiated. Could we have? Should we?

20 Composition with Arrays
If we did instantiate every Student in the roster, we would need to create 50 Student objects public Gradebook() { numberOfStudents = 0; courseName = “”; roster = new Student[50]; for (int c = 0; c < 50; c++) roster[c] = new Student(); } Benefits here are that we are guaranteed at least an object in every roster element (reduced chance of NullPointerException at run-time) Cost is memory usage as you may have a Gradebook object needing only 15 Students

21 Composition with Arrays
Now the overloaded constructors. With class properties that are Arrays, a common design decision is to only focus on the capacity of the Array and not instantiating the elements with actual data public Gradebook(String c) { numberOfStudents = 0; courseName = c; roster = new Student[50]; } Notice numberOfStudents is not set from a given input parameter. Why? Taking this approach relies on updating roster contents by another means…

22 Composition with Arrays
Set methods typically mean to set the value of a given property. However, the roster is an Array You can provide a method to create the roster from a Student array as a parameter, but that may be more for programmer convenience public void setRoster(Student[] r)… A natural way to manage Arrays as a class property is to provide an “add” method public void addStudent(int i, String n) { } What’s the algorithm for this method?

23 Composition with Arrays
One approach for addStudent is to create a new Student object and add it to the roster Array from the given data public void addStudent(int i, String n) { roster[?] = new Student(i, n); } At this point, the roster element is instantiated from given data. Notice that this actually doesn’t require the programmer using the Gradebook class to know what a Student class is! Can we overload addStudent with an input parameter of a Student? Absolutely! But remember this is pass by reference… We’re not done though. Notice the “?” for the index element. What should go here?

24 Composition with Arrays
The correct index element needs to be the next available spot in the roster. We actually already have a property for that! public void addStudent(int i, String n) { roster[numberOfStudents] = new Student(i, n); } numberOfStudents not only represents the number of students in the Gradebook object instance, it also represents the next available element for a new Student object! There’s still a problem with this code though. What is it?

25 Composition with Arrays
numberOfStudents value must be maintained. Since a new Student is being added, we need to increment numberOfStudents public void addStudent(int i, String n) { roster[numberOfStudents++] = new Student(i, n); } Notice the only way Student objects are added to the Gradebook object’s roster Array is through this function. Control over the Array and numberOfStudents is strong (they are also private!) This assumes no gaps in the Array. Makes things interesting for a “removeStudent” function…

26 Composition with Arrays
How does this look from the Gradebook object perspective? public static void main(String[] args) { Gradebook g = new Gradebook(“CIS059”); g.addStudent(111, “John Smith”); g.addStudent(112, “Jane Doe”); } From main, all we know is we are creating a Gradebook object and adding Students from the documentation in the API No concept of a Student class is needed here (but we could if we wanted to allow it) This opens the door for other functions that main could benefit from…

27 Composition with Arrays
Consider what other functions could be useful for main to “request” of the Gradebook object How many Students are currently in the Gradebook? Does a student exist with an ID of 123? How do you remove a Student from the Gradebook? This is also a Gradebook class that probably should maintain information about grades! How should grades be maintained per Student? What is the impact of change to the overall design? One approach is to look at it from the main program perspective and call functions that don’t exist yet to define the signatures you would need

28 Composition with Arrays
public static void main(String[] args) { Gradebook g = new Gradebook(“CIS059”); Student s = new Student(113, “Phil Tayco”, 84.3); g.addStudent(111, “John Smith”, 93.2); g.addStudent(112, “Jane Doe”, 76.8); g.addStudent(s); if (g.exists(112)) System.out.println(g.getStudent(112)); if (g.removeStudent(111)) System.out.println(“Student removed”); g.setGrade(113, 95.5); }

29 Composition with Arrays
All functions used in main here define the signatures needed for Gradebook to support public Gradebook(String) public boolean addStudent(int, string, double) public boolean addStudent(Student) public boolean removeStudent(int) public boolean exists(int) public Student getStudent(int) public boolean setGrade(int, double) public Student(int, String, double) This approach uses main to drive the Gradebook and Student class designs. If agreed to do by the project team, it helps define the minimum requirements for the supporting classes to code

30 Exercise 5 Complete the implementation of the Gradebook and Student classes as discussed in class The code developed tonight will be available to download from the class website If you are using Java to implement your solutions, copy these files into your own project and complete as necessary If you are using another programming language, translate the given code accordingly and complete the implementation You can add more code in main and functiosn to the classes as you see fit or want to try, but avoid changing the code originally provided


Download ppt "Phil Tayco Slide version 1.0 Created Oct 16, 2017"

Similar presentations


Ads by Google