Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
Road Map Introduction to object oriented programming. Classes
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Generics.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
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.
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.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Java SE 8 for Programmers, Third Edition
Data structures Abstract data types Java classes for Data structures and ADTs.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
Peyman Dodangeh Sharif University of Technology Fall 2013.
10-Nov-15 Java Object Oriented Programming What is it?
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
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.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Comp1004: Conclusions Revision Session. Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Comp1202: Conclusions Revision Session. Coming up Key Concepts - The Pillars HashMaps Exceptions The Exam Some Last Words.
Comp1004: Loops and Arrays I Whiles, For and Arrays[]
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Comp1004: Loops and Arrays II
More sophisticated behavior
Encapsulation and Constructors
Java Programming Language
Creating and Modifying Text part 3
Review: libraries and packages
Corresponds with Chapter 5
Presentation transcript:

Comp1004: Environments The Java Library

Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation vs. interface – Example 1: Strings – Example 2: Hashmap

Recap

Encapsulation Take this example class where age is modelled as an int public class Student { int age = 20; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } public int getAge(){ return age; }

Encapsulation public class Student { //int age = 20; Calendar dateOfBirth; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } //public int getAge(){ //return age; //} public int getAge(){ Calendar rightNow = Calendar.getInstance(); int a = calculateAge(rightNow, dateofBirth); return a; } Take this example class where age is modelled as an int We might change the way that age is implemented – e.g. to make it based on the current date. Because we used an Accessor we do not need to alter main

Encapsulation public class Student { //int age = 20; protected Calendar dateOfBirth; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } //public int getAge(){ //return age; //} public int getAge(){ Calendar rightNow = Calendar.getInstance(); int a = calculateAge(rightNow, dateofBirth); return a; } The protected keyword tells Java that only methods in this class* can access this variable. *and its sub-classes, but we’ll come to that later in the course… And yes, public means the opposite – that all other methods can access it!

Constructors public class Student { protected age; public Student() { age = 20; } public Student(int a) { age = a; } public static void main(String[] args){ Student s1 = new Student(19); System.out.println(s1.getAge()); } //code omitted } Constructor Rules: Must have the same name as the class Does not need a return type Can take parameters Can be overloaded Are invoked at the point of creation using the new keyword

Loops int i = 0; while(i < 10){ System.out.println(i); i++; } int i = 0; do { System.out.println(i); i++; } while (i < 10); for (int i = 0; i < 10; i++) { System.out.println(i); } initialization; condition; statechange

Loops for (int i = 0; i < 10; i++) { System.out.println(i); } int i = 0; while(i < 10){ System.out.println(i); i++; } initialization; condition; statechange Condition is checked at start. Loops zero or more times. int i = 0; do { System.out.println(i); i++; } while (i < 10); Condition is checked at end. Loops one or more times. A convenience loop for when we know it advance how many times we want to iterate. Loops zero or more times.

Arrays int[] numStore; numStore = new int[9]; numStore[0] = 77; System.out.println(numStore[0]); [ ] numStore int[] Declaration Instantiation Assignment Retrieval

Iterating Over an Array int numStore = new int[9]; //some missing code to fill the array with values for(int i = 0; i < 9; i++){ System.out.print(“Number at position ” + i); System.out.println(“ is ” + numStore[i]); } Iterating over an array is so common that Java now includes a loop specifically to do it. int numStore = new int[9]; //some missing code to fill the array with values for(int n : numStore){ System.out.println(“Number is ” + n); } Like the for loop the ‘for each’ loop is a shortcut, that is a bit neater than writing the code the long way. But it can only be used for access (e.g. n++ would not increment the value in the array) And it hides the current index

Array vs ArrayList ArrayArrayList Cat[] catArray; catArray = new Cat[10]; catArray[0] = moggy1; catArray[1] = moggy2; callMethodOn(catArray[1]); catArray[0] = null; ArrayList catAList; catAList = new ArrayList(); catAList.add(moggy1); catAList.add(moggy2); callMethodOn(catAList.get(1)); catAList.remove(moggy1); InsertionAccessRemovalDeclaration

Generics ArrayList kennel = new ArrayList(); kennel.add(new Dog(“Rover”)); kennel.add(new Dog(“Fido”)); kennel.add(new Dog(“Patch”)); kennel.add(new Cat(“Mr Tiddles”)); for(int i = 0; i < kennel.size(); i++) { kennel.get(i).bark(); } ArrayLists store objects of any type Which means we can mix up the types of objects in the ArrayList Which may cause problems later if we make assumptions about what is in there! In fact this code will not compile, because Java does not know what is in the ArrayList, and therefore will not let you call bark on it

Generics ArrayList kennel = new ArrayList (); kennel.add(new Dog(“Rover”)); kennel.add(new Dog(“Fido”)); kennel.add(new Dog(“Patch”)); kennel.add(new Cat(“Mr Tiddles”)); for(int i = 0; i < kennel.size(); i++) { kennel.get(i).bark(); } It would be better if we could ensure that the ArrayList only contained Dogs in the first place This is easily done because ArrayList uses a mechanism called generics. We can specify the type allowed when we create the ArrayList. Now Java will only allow us to add things of type Dog. So this line will force a compile time error

Iterators ArrayList kennel = new ArrayList (); kennel.add(new Dog(“Rover”)); kennel.add(new Dog(“Fido”)); kennel.add(new Dog(“Patch”)); for(int i = 0; i < kennel.size(); i++) { kennel.get(i).bark(); } Iterator it = kennel.iterator(); while(it.hasNext()) { it.next().bark(); } 1) They are neater, and neat code is easier to read and understand 2) They decouple the loop from the collection (notice that in the loop we do not reference the Arraylist at all) This means we could pass the iterator to a method – and that method does not even need to know what the collection is!

Iterators public void makeThemBark(Iterator it) { while(it.hasNext()) { it.next().bark(); } 1) They are neater, and neat code is easier to read and understand 2) They decouple the loop from the collection (notice that in the loop we do not reference the Arraylist at all) This means we could pass the iterator to a method – and that method does not even need to know what the collection is!

The Java Library

Library The java library is full of helpful classes Like ArrayList What does the inside of an ArrayList look like? How does it handle the resizing? How does it know when the throw an error? How does it handle renumbering when removing elements?

Implementation vs. Interface Because of encapsulation all we need to know to use the ArrayList class, and the other library classes is what their interface is A Class’ interface is how we interact with the class – It’s public variables and methods – what methods we can call – what they do – what they will return

Importing Library classes must be imported using an import statement import java.util.ArrayList; public class myClass{ ArrayList arrl; arrl = new ArrayList ; public static void main(String[] args){ //code omitted }

Importing packages Classes are organised in packages. Single classes may be imported: import java.util.ArrayList; Whole packages can be imported: import java.util.*;

Where is the Library? All library classes are included in the Java runtime and development environments All the documentation is available online: –

Example 1: Strings

Strings Strings are actually objects – Did you notice we always use a capital S like other classes? You don’t need to import them – they are from the automatically imported from java.lang.*; As is System as in System.out.println()

A word about comparing Strings if(input == “hello") { //code here } if(input.equals(“hello")) { //code here } You probably mean to compare strings using.equals

identity vs equality name1 String Harry Ron name2 String Tom name1 == name2 False, different addresses name1.equals(name2) False, different value String name1 = “Harry”; String name2 = “Tom”;

identity vs equality name1 String Harry Ron name2 String Harry String name1 = “Harry”; String name2 = “Harry”; name1 == name2 False, different addresses name1.equals(name2) True, same value

identity vs equality name1 String Harry name2 String String name1 = “Harry”; String name2 = name1; name1==name2 True, same address name1.equals(name2) True, same value

Example 2: Hashmaps

Maps Maps are a collection type that map a key to a value put(“Alfie”,“407351”); and so on Memory Map: Name -> Phone number Alfie Jenny

Lookup Lookup is the act of supplying the key and having the value returned String num = myHashMap.get(“Alfie”); Memory myHashMap Alfie

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob"));

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob")); What is this?

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob")); What is this? HashMap is a generic class, this means we should tell it what two types it maps together

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob")); What is this? HashMap is a generic class, this means we should tell it what two types it maps together What is happening here?

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob")); What is this? HashMap is a generic class, this means we should tell it what two types it maps together What is happening here? This is autoboxing – the ints are automatically turned into Integers for us

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob")); What is this? HashMap is a generic class, this means we should tell it what two types it maps together What is happening here? This is autoboxing – the ints are automatically turned into Integers for us Which type of String comparison is being used?

Bringing it together… import java.util.HashMap; //code omitted HashMap marks; marks = new HashMap (); marks.put("Alice", 75); marks.put("Bob", 62); marks.put("Colin", 68); System.out.println("Bob got " + marks.get("Bob")); What is this? HashMap is a generic class, this means we should tell it what two types it maps together What is happening here? This is autoboxing – the ints are automatically turned into Integers for us Which type of String comparison is being used? Equality (not Identity). It is using the.equals method

Summary Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Class interface – Example 1: Strings – Example 2: Hashmap