Java the UML Way versjon 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and.

Slides:



Advertisements
Similar presentations
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Advertisements

Comparable and Comparator Nuts and Bolts. 2 Nuts and bolts Four methods underlie many of Java’s important Collection types: equals, compare and compareTo,
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Java Syntax Primitive data types Operators Control statements.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
1 More on Arrays Arrays of objects Command line arguments The ArrayList class Javadoc Review Lecture 8 notes and L&L 7.1 – 7.2 Reading for this lecture:
Comparable and Comparator. 2 Comparing our own objects The Object class provides public boolean equals(Object obj) and public int hashCode() methods –For.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Object Oriented Programming Lecture 2: BallWorld.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
TCSS 143, Autumn 2004 Lecture Notes
Comparable and Comparator
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Java Classes and Objects 3rd Lecture
Comparable and Comparator
Grouped Data Arrays, and Array Lists.
Java Programming Language
Creating and Modifying Text part 3
Arrays.
Presentation transcript:

Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10 Arrays of Reference Types and Array Lists An Array of Reference Typepage 2-4 ArrayListpage 5-6 Wrapper classes for primitive data typespage 7-8 The equals() and toString() methodspage 9 Assosiations / registerspage Java Interfacepage 16 Ready-made methods for sorting and searching, with Comparablepage An alternative to Comparablepage 19 Sorting according to locationpage 20 Ready-made methods for sorting and searching, with Comparatorpage 21

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 2 An Array of References, Strings as an Example –Every element in the array is a reference to String: String[] names = new String[4]; –This is an array of references. Every one of these has to point to an instance of the String class: names[0] = new String(”Anne”); names[1] = ”Thomas”; // short form is ok –The reference may be a return value from a method creating a String object: names[2] = JOptionPane.showInputDialog("Write a name: "); names[3] = names[0].toUpperCase(); –Or we may write: String[] names = {”Anne”, ”Thomas”, ”Edward”, ”ANNE”}; names AnneThomasEdwardANNE

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 3 Copying an Array of References Does Not Copy the Objects names AnneThomasEdwardANNE copyOfNames String[] copyOfNames = new String[4]; for (int i = 0; i < names.length; i++) { copyOfNames[i] = names[i]; }

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 4 Array Elements of Primitive Data Type vs. Reference Type An array of a primitive data type: –The elements in the array contain the data values. –Comparisons and assignments between elements directly affect the data values. The data values are compared and copied. –The elements in the array are initialized to 0 (or false) if nothing else is said in the declaration. An array of a reference data type: –The elements in an array of reference type are references, not objects. –The references in an array get the initial value null. –Every individual reference in the array has to be set to refer to an object before it can be used. If we try to use an array element that does not refer to any object, a NullPointerException is thrown. –We can’t use comparison operators other than == and != on elements like these. The operator == returns true if the elements refer to the same objects. –Assignment means the reference changes value, in other words it is set to refer to another object. The objects remain untouched. They are neither moved nor copied. Solve the problems 1-4, pp

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 5 What is an ArrayList? Ordinary arrays are not very flexible. The size cannot be changed after the array is created. An instance of the java.util.ArrayList class –has a built-in array of references. –maintains the size of this array as required, by itself. –knows how much of the built-in array is in use. Methods: –boolean add(Object obj) – insert a reference into the array list –Object get(int indeks) – get a reference from the array list –Object remove(int indeks) – remove a reference from the array list –int size() – the number of references stored in the array list If invalid index in the get() or remove() methods, an IndexOutOfBoundsException is thrown If a parameter is of the Object type (java.lang.Object), the argument can be from any reference type whatsoever. If the return type from a method is Object, we have to cast the return object to the right class before we can send messages to it.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 6 An Example import java.util.*; class TestArrayList { public static void main(String[] args) { String name1 = new String("Edward"); String name2 = new String("John"); String name3 = new String("Elizabeth"); ArrayList name = new ArrayList(); name.add(name1); name.add(name2); name.add(name3); for (int i = 0; i < name.size(); i++) { String aName = (String) name.get(i); System.out.println(aName); } /* Printout: Edward John Elizabeth */ Problem: Draw a figure showing all references and objects in this program. Solve all problems, page 278.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 7 What About Storing Numbers in an ArrayList? The elements in an array list have to be references. The classes Integer, Double, etc wrap a value of a primitive data type into an object. These classes are wrapper classes for the primitive data types. References to these wrapper objects may be stored in an array list. Examples: –Integer integerObject = new Integer(50); // creates an object with value 50 –int number = integerObject.intValue(); // fetches the number value out of the object We input positive numbers from the user and store them in an array list: ArrayList numbers = new ArrayList(); int aNumber = InputReader.inputInteger("Write a positive number: "); // see chap. 6.8 while (aNumber > 0) { Integer integerObject = new Integer(aNumber); numbers.add(integerObject); aNumber = InputReader.inputInteger("Write a positive number: "); }

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 8 The Wrapper Classes for the Primitive Data Types Class names: Integer, Long, Float, Double, Byte, Character and Boolean The classes belong to the java.lang package. All the classes are immutable. Every class has a constructor taking a value of the corresponding primitive data type as an argument. Every class, except for Character, has a constructor taking a string as argument. The constructor throws a NumberFormatException if conversion is not possible. An example, the Integer class: –Integer(int value) –Integer(String s) throws NumberFormatException –String toString() –static int parseInt(String s) throws NumberFormatException –static String toString(int i) An example: String t = "234_567"; try { int number = Integer.parseInt(t); System.out.println("The number is " + number); } catch (NumberFormatException e) { System.out.println("Cannot convert " + t+ " into number"); System.out.println(e); } Printout: Cannot convert 234_567 into number java.lang.NumberFormatException: 234_567 Solve problem 1, page 281.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 9 The equals() and toString() Methods All classes are subclasses of the java.lang.Object class All classes inherit the methods of the Object class, among others: –public String toString() returns the name of the class the object is an instance of, followed and a number code –public boolean equals(Object obj) compares the reference this with the reference obj, returns true if they are equal But – a class can (and should!) have its own versions of these methods. If it has, it is these versions which apply for instances of the class. The methods should be programmed with this functionality: –toString() should return a string which the client could use to get a printout of the contents of the object. –equals() should compare the contents of the objects The toString() method is implied –if we link an object to a string with the + operator, e.g.: string result = "The account: " + acconut1; –if we use an object as argument to System.out.println(), e.g.: System.out.println(account1); Solve the problem, page 283.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 10 Associations An association between classes means that there is a connection between instances of the classes. Examples: ApartmentSurface 6..* 1..1 consists of multiplicity name with reading direction indicated Person Office 1 1 stays at BookAuthor 1..* is written by

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 11 The Renovation Case, One More Time Input about surface: name, length, width, type of paint. Input about type of paint: name, no. of coats, no. of sq.m/l, price per liter

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 12 The Renovation Case, Associations We separate classes describing the user interface from classes describing the problem we're solving. This makes it easy to change between different kinds of user interfaces. Here we look at classes describing the problem:

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 13 Programming Associations A register emerges as a one-to-many association between the class that is responsible for maintaining the register and the class that is describing the objects that are included in the register. –An instance of the RenovationProject class maintains two registers, one containing information about the surfaces, the other containing information about the different types of paint. We create a register by creating an array list. This array list will contain references to the objects that are stored in the register. class RenovationProject { private String name; private ArrayList allSurfaces = new ArrayList(); private ArrayList allPaints = new ArrayList(); The association between Surface and Paint should be programmed in another way. An instance of the Paint class doesn't need to know about all the Surface instances. The opposite is true: A Surface object needs to know with which type of paint it will be covered. We program this by creating a reference to this object in the Surface class: class Surface { private String name; // for identification purposes private double length; private double width; private Paint paint;

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 14 Which Tasks Should a Register Object be Able to Perform? In general, a client would ask for the following services: –Adding data to the register. –Looking at all data already stored in the register. –Searching in the register, given e.g. a name. –Removing data. –Editing data. We'll look at the registers in the renovation case as an example. (Removing and editing data are not implemented, but see the problems on page 295.)

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 15 Show Program Listing 10.1, pp Problems: –In a client program we have an object: RenovationProject project = new RenovationProject (”MyHouse”); –Several surfaces and several types of paint are already registered. –Expand the client program with the following: 1.Create and register a new surface object. You'll need constructors: –public Surface(String initName, double initLength, double initWidth) –public Paint(String initName, double initPrice, int initNoOfCoats, double initNoOfSqMPerLiter) 2.Find out if a paint with name”Huldra 8” exist? 3.Print the names of all the registered surfaces. 4.Expand the loop with the name of the paint that is used for every surface.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 16 Interface A Java interface, simply put, is a collection of method heads. A class can choose to implement an interface. Then all the methods in the interface have to be programmed. An example from the java.lang package is: public interface Comparable { public int compareTo(Object obj); } Example of a class implementing this interface: class Surface implements Comparable { public int compareTo(Object obj) { // comparing areas Surface theOtherSurface = (Surface) obj; double area1 = getArea(); // the area of this double area2 = theOtherSurface.getArea(); if (area1 < area ) return -1; // comparing decimal numerals else if (area1 > area ) return 1; else return 0; } Solve the problem, page 297.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 17 How is it Possible to Create Generic Methods for Sorting and Searching? A generic method for sorting or searching will have to compare objects. Different kinds of objects should be compared in different ways. An instance of one class should be compared by another instance of the same class by sending a message to the first instance: name1.compareTo(name2) The class which the instances belong to, should offer the compareTo() method. A generic method for sorting or searching is possible if the head of the comparing method is the same for all types of objects. We create an interface containing the method head, and then we require that all the objects which should be sorted (or searched in) belongs to classes that implement this interface. Comparable is just this interface: public interface Comparable { // belongs to the java.lang package public int compareTo(Object obj); }

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 18 Sorting and Searching Methods from the Java API, Using Comparable The objects should belong to classes implementing the Comparable interface. The java.util.Arrays offers methods for arrays: –static int binarySearch(Object[] array, Object[] value) –static void sort(Object[] array) –static void sort(Object[] array, int fromIndex, int toIndex) Exceptions may be thrown: ArrayIndexOutOfBoundsException, IllegalArgumentException, ClassCastException The java.util.Collections offers methods for array lists: –static int binarySearch(List arrayList, Object value) –static void sort(List arrayList) The ArrayList class implements the List interface, therefore it is ok that the first parameter is of the List type.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 19 An Alternative to Comparable We create an object containing complete information about the sorting order of "the main objects". Such an object has to belong to a class implementing the Comparator interface: public interface Comparator { // belongs to the java.util package public int compare(Object o1,Object o2) public boolean equals(Object obj) } The java.text.Collator is a useful example of a class implementing the Comparator interface –An instance of this class contains information about the sorting order of strings according to a given location. public static Collator getInstance() public static Collator getInstance(Locale givenLocation) public int compare(String text1, String text2) public void setStrength(int newStrength) // PRIMARY, SECONDARY, TERTIARY

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 20 Sorting Strings According to the Default Settings public static void sortTextLocale(String[] array) { Collator collator = Collator.getInstance(); for (int start = 0; start < array.length; start++) { int smallestToNow = start; for (int i = start + 1; i < array.length; i++) { if (collator.compare(array[i], array[smallestToNow]) < 0) smallestToNow = i; } String help = array[smallestToNow]; array[smallestToNow] = array[start]; array[start] = help; } public static void sortIntegerArray(int[] array) { for (int start = 0; start < array.length; start++) { int smallestToNow = start; for (int i = start + 1; i < array.length; i++) { if (array[i] < array[smallestToNow]) smallestToNow = i; } int help = array[smallestToNow]; array[smallestToNow] = array[start]; array[start] = help; } Sorting integers, pp Sorting strings, pp

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 10, page 21 Sorting and Searching Methods from the Java API, using Comparator These methods use a ”Comparator” to compare the objects. The java.util.Arrays offers methods for arrays: –static int binarySearch(Object[] array, Object[] value, Comparator comp) –static void sort(Object[] array, Comparator comp) –static void sort(Object[] array, int fromIndex, int toIndex, Comparator comp) Exceptions may be thrown: ArrayIndexOutOfBoundsException, IllegalArgumentException, ClassCastException The java.util.Collections offers methods for array lists: –static int binarySearch(List arrayList, Object value, Comparator comp) –static void sort(List arrayList, Comparator comp) The ArrayList class implements the List interface, therefore it is ok that the first parameter is of the List type. Solve all problems, page