Grouping Objects (I)

Size: px
Start display at page:

Download "Grouping Objects (I)"

Transcription

1 KTH ROYAL INSTITUTE OF TECHNOLOGY Stockholm Sweden Grouping Objects (I) Managing collections of objects Ric Glassey

2 Main concepts to be covered Grouping Objects Using ArrayLists Looping with for-each syntax Collections in Java Generics 2

3 Grouping Objects 3

4 The requirement to group objects Many applications involve grouping objects: Personal organizers Library catalogs Student-record system The number of items varies across application lifecycle Items can be added Items can be accessed / modified Items be removed 4

5 QueueSystem Association with Aggregation of UserInterface Question User Inherits from FrontEnd Backend Student Assistant Administrator 5

6 Is this the best solution? class QueueSystem { // fields private User alice; private User bob; private User carol; private Question question1; private Question question2; private Question question3; private Question question4; // etc // constructors // methods 6

7 BlueJ Project: Music Organiser Manages a group of music files as String objects Track files may be added There is no limit to the number of files Mutable vs. Immutable groups Reports the current number of stored files Individual file names can be retrieved 7

8 Demo: Music Organiser v1 8

9 Using ArrayLists 9

10 Class Libraries in Java We don t have to write everything from scratch Most common problems have trusted solutions Official libraries of code 3rd Party libraries Java calls its libraries: packages Grouping objects is a recurring requirement The java.util package contains classes for doing this. 10

11 READ THE MANUAL

12 import java.util.arraylist; /** *... */ public class MusicOrganizer { // Storage for an arbitrary number of file names. private ArrayList<String> files; /** * Perform any initialization required for the * organizer. */ public MusicOrganizer() { files = new ArrayList<String>();... 12

13 The ArrayList Collection Java has a set of collections that vary in shape and behaviour (Lists, Maps, Sets, etc) ArrayList is a simple linear sequence of objects To use, we specify: the type of collection: ArrayList the type of objects it will contain: <String> private ArrayList<String> files; ArrayList of Strings called files 13

14 The ArrayList Collection ArrayList implements a List interface consisting of common operations on all Lists: add, get, size, etc. All Java collections are parameterised or generic types Most often, a collection will contain objects of a class By default, collections will accept multiple classes This should be avoided and collections should be parameterised The type parameter declares what we want a list of: ArrayList<Person> ArrayList<TicketMachine> 14

15 Creating an ArrayList object In versions of Java prior to version 7: files = new ArrayList<String>(); Java 7 introduced diamond notation files = new ArrayList<>(); The type parameter can be inferred from the earlier variable declaration statement: private ArrayList<String> files; 15

16 Object structures with collections 16

17 Adding a third file 17

18 Behaviour of the ArrayList It increases its capacity as necessary (mutable) It keeps a private count: size() accessor It keeps the objects in order Details of how all this is done are hidden Does that matter? Does not knowing how prevent us from using it? 18

19 Using the collection public class MusicOrganizer { private ArrayList<String> files;... public void addfile(string filename) { files.add(filename); Adding a new file public int getnumberoffiles() { return files.size(); Returning the number of files (delegation)... 19

20 Index numbering n.b. index starts from 0 20

21 Retrieving an object public void listfile(int index) { if(index >= 0 && index < files.size()) { String filename = files.get(index); System.out.println(filename); else { // This is not a valid index. Index validity checks Retrieve and print the file name Needed? (Error message?) 21

22 Removal may affect numbering 22

23 The general utility of indices Using integers to index collections has a general utility: next is: index + 1 previous is: index 1 last is: list.size() 1 the first three is: the items at indices 0, 1, 2 We could also think about accessing items in sequence: 0, 1, 2, 23

24 Review Collections allow an arbitrary number of objects to be stored via a single object e.g. files Class libraries usually contain tried-and-tested collection classes (official + 3rd party) Java s class libraries are called packages We have used the ArrayList class from the java.util package 24

25 Review Items may be added and removed via methods Each item has an index Index values may change if items are removed (or further items added) The main ArrayList methods are add, get, remove and size ArrayList is a parameterised or generic type 25

26 Demo: Music Organizer v2 26

27 Looping with for each syntax 27

28 Iteration We often want to repeatedly perform some action a number of times (e.g. iteration) E.g., print all the file names in the organizer. How many are there? Most programming languages include loop statement syntax to make iteration convenient Java has several sorts of loop statement We will start with its for-each loop Next week: for, while and Iterator objects 28

29 Iteration Strategies Visit all elements in a collection; perform action Visit all elements; selectively perform action Visit some elements until condition satisfied Visit some elements, but Starting and end point can vary Order is altered or reversed Not in natural sequence (stepping or skipping) Visit some or all elements; modify collection concurrently 29

30 For-each loop pseudo code General form of the for-each loop for keyword loop header for(elementtype element : collection) { loop body Statement(s) to be repeated Pseudo-code expression of the actions of a for-each loop For each element in collection, do the operations in the loop body. 30

31 Demo: Music Organizer v3 31

32 A Java example /** * List all file names in the organizer. */ public void listallfiles() { for(string filename : files) { System.out.println(filename); for each filename in files, print out filename 32

33 Selective processing Statements can be nested, giving greater selectivity: public void findfiles(string searchstring) { for(string filename : files) { if(filename.contains(searchstring)) { System.out.println(filename); 33

34 Critique of for-each Easy to write Termination happens naturally Some awkward questions for for-each loops: Can we start at a particular point in the collection? Can we step through / skip multiple objects? Can we stop mid-loop? Can we update the collection mid-loop? Explanation? Abstraction 34

35 Looping Review Loop statements conveniently allow a block of statements to be repeated many times The for-each loop allows iteration over a whole collection of objects Each object is guaranteed to be visited (definite iteration) Useful as this is the most common use-case Limitations: Indefinite iteration is not supported Index manipulation is not supported Concurrent collection modification is not supported 35

36 Short Syntax Quiz 36

37 What s wrong here? /** * Print out info (number of entries). */ public void showstatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); else { System.out.print("Organizer holds "); System.out.println(files.size() + " files"); 37

38 This is the same as before! /** * Print out info (number of entries). */ public void showstatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); 38

39 This is the same again /** * Print out info (number of entries). */ public void showstatus() { if(files.size() == 0) ; { System.out.println("Organizer is empty"); else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); 39

40 and the same again /** * Print out info (number of entries). */ public void showstatus() { if(files.size() == 0) { ; { System.out.println("Organizer is empty"); else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); 40

41 What s wrong here? /** * Print out info (number of entries). */ public void showstatus() { if(isempty = true) { System.out.println("Organizer is empty"); else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); 41

42 The correct version /** * Print out info (number of entries). */ public void showstatus() { if(isempty == true) { System.out.println("Organizer is empty"); else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); 42

43 What s wrong here? /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addfile(string filename) { if(files.size() == 100) files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); 43

44 This is the same. /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addfile(string filename) { if(files.size == 100) files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); 44

45 The correct version /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addfile(string filename) { if(files.size == 100) { files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); 45

46 Collections in Java 46

47 Collections Framework Collections (like ArrayList) are essentially containers Store, retrieve, manipulate and communicate aggregations of objects Convenience for grouping objects in applications Java provides a Collections Framework Unified architecture for representing and manipulating multiple kinds of collections Common interface and operations 47

48 Collections Framework: Contents Interfaces (e.g. List) Provides a common vocabulary for interacting with a particular kind of collection, independent of its implementation details (info hiding) Implementations (e.g. ArrayList) Concrete implementations that are ready to use Algorithms (e.g. sort) Common operations that are required over collections independent of the objects 48

49 Collection Interface All collections derive from this interface List, Set, Map, Queue Supports operations common to all collections int size( ) boolean isempty( ) boolean containsobject(object element) boolean add(object element) boolean remove(object element) 49

50 List Interface & Implementation Extends from Collection interface Ordered collection or sequence Can contain duplicates Additional specific operations (level of detail) positional access, e.g. get, set, add search for object and return position/index iteration across elements in sequence The ArrayList and LinkedList are implementations 50

51 import java.util.*; class ListTest { public static void main(string[] args) { // Change to LinkedList and compare the time difference :) List<Integer> mylist = new ArrayList<>(); int size = ; // Add numbers to mylist for (int i=size; i>0 ; i-- ) { mylist.add(i); // Time the sort algorithm long start = System.nanoTime(); Collections.sort(myList); long stop = System.nanoTime(); // Print the runtime in nanoseconds System.out.println(stop-start);

52 Common Algorithms Many useful operations have been included and optimised for performance and stability sort shuffle reverse frequency etc 52

53 Common Algorithms import java.util.*; class Sorting { public static void main(string[] args) { ArrayList<String> words = new ArrayList<>(); words.add("what"); words.add("a"); words.add("wonderful"); words.add("day"); words.add("to"); words.add("code!"); Collections.sort(words); System.out.println(words); 53

54 Collections Framework: Benefits Reduces programmer effort Increases speed and quality Reduces learning effort Reduces complexity of creating new collections Encourages software reuse Very important to DD1338 in that we will be implementing their underlying behaviour and investigating their properties in time/space complexity 54

55 Generics 55

56 Motivation Java is statically typed and thus allows a lot of type-related bugs to be detected by the compiler Raw Type collections (no parameterisation) were default prior to Java 5.0 Collections could store any type without problem However this leads to potential runtime bugs 56

57 Raw Type vs Parameterised ArrayList myintlist = new ArrayList(); myintlist.add(new Integer(100)); myintlist.add(200); // auto-boxing // note use of type-casting operation Integer x = (Integer) myintlist.get(0); Integer y = (Integer) myintlist.get(1); 57

58 Raw Type vs Parameterised ArrayList<Integer> myintlist = new ArrayList<>(); myintlist.add(new Integer(100)); myintlist.add(200); Integer x = myintlist.get(0); Integer y = myintlist.get(1); Much better, but why? Less typing? 58

59 Raw Type vs Parameterised ArrayList myintlist = new ArrayList(); myintlist.add(new Integer(100)); // compiler is ok with that myintlist.add("200"); // oops! // note use of type-casting operation Integer x = (Integer) myintlist.get(0); // potential class cast exception at runtime Integer y = (Integer) myintlist.get(1); Any object can be added to collection 59

60 Raw Type vs Parameterised ArrayList<Integer> myintlist = new ArrayList<>(); myintlist.add(new Integer(100)); // compile-time error myintlist.add("200"); Integer x = myintlist.get(0); Integer y = myintlist.get(1); The compiler is once again helping 60

61 Creating Generic Classes Most often encountered when using collections You may create your own Provides stronger type checking at compilation Eliminates the need for cast operations We need to add new syntax to class definitions Formal type declarations 61

62 A basic container First, we make a simple class that can contain any object n.b It allows any type to be added, and may need cast operations, e.g. using + operator Then, we try to use generics to make it safer and with no need for casts 62

63 public class Container { private Object o; public void set(object o) { this.o = o; public Object get() { return this.o; public static void main(string[] args) { Container c = new Container(); c.set(10); c.set("10"); System.out.println(c.get()); 63

64 public class Container2<T> { private T t; public void set(t t) { this.t = t; public T get() { return this.t; public static void main(string[] args) { Container2<Integer> c = new Container2<>(); c.set(10); c.set( 10"); // will throw compile error System.out.println(c.get()); 64

65 Generics Roundup Emphasis on type safety and readability Generics will become more useful as we create our own collections in DD1338 The final version of Music Organiser (v5) highlights: use of collections use of class libraries (official and 3rd party) use of generics 65

66 Demo: Music Organizer v5 66

67 Concept Review 67

68 Concept Review Grouping objects together is another important form of abstraction in Java Java commonly refers to groups of objects as a collection The ArrayList stores a mutable sequence of (parameterised) objects and provides methods to manipulate the grouped objects 68

69 Concept Review The for each looping strategy provides a simple approach to iterating across an entire collection of objects, but has limitations Every object will be visited Does not support index manipulation, indefinite iteration and concurrent modification 69

70 Concept Review In Java, the collections framework provides a set of interfaces to common collection types and a set of common operations/methods to manipulate them Generics provide a convenient manner of introducing more type safety and less type conversions by removing cast operations 70

71 *Required Reading* Chapter 4 Sections 4.1 to 4.11 Objects First with Java, 4th/5th Edition Optional Texts! Code Complete and Effective Java 71

CITS1001 week 4 Grouping objects

CITS1001 week 4 Grouping objects CITS1001 week 4 Grouping objects Arran Stewart March 20, 2018 1 / 31 Overview In this lecture, we look at how can group objects together into collections. Main concepts: The ArrayList collection Processing

More information

Grouping objects. The requirement to group objects

Grouping objects. The requirement to group objects Grouping objects Introduction to collections 4.0 The requirement to group objects Many applications involve collections of objects: Personal organizers. Library catalogs. Student-record system. The number

More information

Grouping objects. Main concepts to be covered

Grouping objects. Main concepts to be covered Grouping objects Collections and iterators 3.0 Main concepts to be covered Collections Loops Iterators Arrays Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling

More information

Scope of this lecture. Repetition For loops While loops

Scope of this lecture. Repetition For loops While loops REPETITION CITS1001 2 Scope of this lecture Repetition For loops While loops Repetition Computers are good at repetition We have already seen the for each loop The for loop is a more general loop form

More information

Grouping objects Lecture 7

Grouping objects Lecture 7 Grouping objects Lecture 7 Waterford Institute of Technology February 2, 2016 John Fitzgerald Waterford Institute of Technology, Grouping objects Lecture 7 1/36 Presentation outline Estimated duration

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed 1 1 COMP200 GENERICS OOP using Java, from slides by Shayan Javed 2 ArrayList and Java Generics 3 Collection A container object that groups multiple objects 4 Collection A container object that groups multiple

More information

CITS1001 week 6 Libraries

CITS1001 week 6 Libraries CITS1001 week 6 Libraries Arran Stewart April 12, 2018 1 / 52 Announcements Project 1 available mid-semester test self-assessment 2 / 52 Outline Using library classes to implement some more advanced functionality

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Object-Oriented Programming Intro Department of Computer Science University of Maryland, College Park Object-Oriented Programming (OOP) Approach to improving software

More information

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs 1 Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs Michael Albert michael.albert@cs.otago.ac.nz Keywords: abstract data type, collection, generic class type, stack 2 Collections

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

CITS1001 week 4 Grouping objects lecture 2

CITS1001 week 4 Grouping objects lecture 2 CITS1001 week 4 Grouping objects lecture 2 Arran Stewart March 29, 2018 1 / 37 Overview Last lecture, we looked at how we can group objects together into collections We looked at the ArrayList class. This

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

Advanced Programming Generics Collections

Advanced Programming Generics Collections Advanced Programming Generics Collections The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

Lesson 26: ArrayList (W08D1)

Lesson 26: ArrayList (W08D1) Lesson 26: ArrayList (W08D1) Balboa High School Michael Ferraro October 5, 2015 1 / 25 Do Now Prepare PS #4a (paper form) for pick-up! Consider the code below for powiter(), an iterative algorithm that

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

STUDENT LESSON A15 ArrayList

STUDENT LESSON A15 ArrayList STUDENT LESSON A15 ArrayList Java Curriculum for AP Computer Science, Student Lesson A15 1 STUDENT LESSON A15 - ArrayList INTRODUCTION: It is very common for a program to manipulate data that is kept in

More information

Java Collections Framework: Interfaces

Java Collections Framework: Interfaces Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods 6 Defining the idea Behind Java Generics Data Types are now used as TypeParameters 7 Defining the idea Behind Java

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Building Java Programs

Building Java Programs Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4, 16.4-16.5 2 A tree set Our SearchTree class is essentially a set. operations: add, remove, contains, size, isempty similar

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

Object-oriented programming in...

Object-oriented programming in... Programming Languages Week 12 Object-oriented programming in... College of Information Science and Engineering Ritsumeikan University plan this week intro to Java advantages and disadvantages language

More information

11/2/ Dynamic Data Structures & Generics. Objectives. Array-Based Data Structures: Outline. Harald Gall, Prof. Dr.

11/2/ Dynamic Data Structures & Generics. Objectives. Array-Based Data Structures: Outline. Harald Gall, Prof. Dr. 12. Dynamic Data Structures & Generics Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch Objectives! Define and use an instance of ArrayList! Describe general idea

More information

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 Name: This exam consists of 5 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

C++ (Non for C Programmer) (BT307) 40 Hours

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

Curriculum Map Grade(s): Subject: AP Computer Science

Curriculum Map Grade(s): Subject: AP Computer Science Curriculum Map Grade(s): 11-12 Subject: AP Computer Science (Semester 1 - Weeks 1-18) Unit / Weeks Content Skills Assessments Standards Lesson 1 - Background Chapter 1 of Textbook (Weeks 1-3) - 1.1 History

More information

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types generics enable types (classes and interfaces) to be parameters when defining

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Slides are adapted from the originals available at

Slides are adapted from the originals available at C H A P T E R 1 1! Arrays and ArrayLists Little boxes, on a hillside, little boxes made of ticky-tacky Little boxes, little boxes, little boxes, all the same There s a green one and a pink one and a blue

More information

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

Lab Activity Plan. John Dalbey CPE /30/2013

Lab Activity Plan. John Dalbey CPE /30/2013 John Dalbey CPE 13-5 9/3/213 Lab Activity Plan Purpose The purpose of this lab is to demonstrate the performance impacts of autoboxing in Java. The textbook describes how Java will automatically convert

More information

Collections of Objects. Object Oriented Programming Camilo López

Collections of Objects. Object Oriented Programming Camilo López Collections of Objects Object Oriented Programming 2016375-5 Camilo López Outline What are Collections? Arrays as Simple Collections ArrayList HashMap TreeMap Simultaneous References Revisiting the Student

More information

Topic 10: The Java Collections Framework (and Iterators)

Topic 10: The Java Collections Framework (and Iterators) Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 19 19:36:29 2017 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

Building Java Programs

Building Java Programs Building Java Programs A Back to Basics Approach Stuart Reges I Marty Stepp University ofwashington Preface 3 Chapter 1 Introduction to Java Programming 25 1.1 Basic Computing Concepts 26 Why Programming?

More information

CS Introduction to Data Structures Week 1 Thursday

CS Introduction to Data Structures Week 1 Thursday CS 367 - Introduction to Data Structures Week 1 Thursday We assume that you are proficient at object-oriented programming in Java. Please enroll in CS300 if you do not know Java and have not written object-oriented

More information

Synchronization SPL/2010 SPL/20 1

Synchronization SPL/2010 SPL/20 1 Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

More on collec)ons and sor)ng

More on collec)ons and sor)ng More on collec)ons and sor)ng CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2013 Java Collec/ons API Overview List (last term), e.g. ArrayList Map (last /me), e.g. HashMap Set

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards

More information

CS 314 Midterm 2 Fall 2012

CS 314 Midterm 2 Fall 2012 Points off 1 2 3 4 5 Total off Net Score CS 314 Midterm 2 Fall 2012 Your Name_ Your UTEID Circle yours TA s name: John Zihao Instructions: 1. There are 5 questions on this test. 2. You have 2 hours to

More information

AP CS Unit 7: Interfaces. Programs

AP CS Unit 7: Interfaces. Programs AP CS Unit 7: Interfaces. Programs You cannot use the less than () operators with objects; it won t compile because it doesn t always make sense to say that one object is less than

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

CS 520 Theory and Practice of Software Engineering Fall 2017

CS 520 Theory and Practice of Software Engineering Fall 2017 Logistics CS 520 Theory and Practice of Software Engineering Fall 2017 Best and worst programming practices September 12, 2017 Recap: software architecture vs. design Recap: software architecture examples

More information

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods Main concepts to be covered Understanding class definitions Looking inside classes fields constructors methods parameters assignment statements 5.0 2 Ticket machines an external view Exploring the behavior

More information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm CSC 172 Data Structures and Algorithms Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm Agenda Administrative aspects Java Generics Chapter 1 ADMINISTRATIVE ASPECTS Workshops Workshops Workshops begin on this

More information

CS 520 Theory and Practice of Software Engineering Fall 2017

CS 520 Theory and Practice of Software Engineering Fall 2017 CS 520 Theory and Practice of Software Engineering Fall 2017 Best and worst programming practices September 12, 2017 Logistics Recap: software architecture vs. design Specification Architecture Development

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 18 21:04:53 2018 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

Lists using LinkedList

Lists using LinkedList Lists using LinkedList 1 LinkedList Apart from arrays and array lists, Java provides another class for handling lists, namely LinkedList. An instance of LinkedList is called a linked list. The constructors

More information

CSE 143 Lecture 20. Circle

CSE 143 Lecture 20. Circle CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public

More information

Binghamton University. CS-140 Fall Chapter 7.7. Lists. Java Library Data Structures

Binghamton University. CS-140 Fall Chapter 7.7. Lists. Java Library Data Structures Chapter 7.7 Lists Java Library Data Structures 1 Java Library Data Structures A data structure is a way of organizing data The Java Library supports many different data structures Let s start with one

More information

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University Lecture 6 COMP1006/1406 (the OOP course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments A1,A2,A3 are all marked A4 marking just started A5 is due Friday, A6 is due Monday a quick

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

Week 16: More on Collections and Immutability

Week 16: More on Collections and Immutability Week 16: More on Collections and Immutability Jack Hargreaves jxh576@cs.bham.ac.uk Febuary 9, 2012 1 Collections API Last week we looked at Collection, List, Set and Map the basic data type interfaces

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s). AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s). a) This code will not compile because a method cannot specify an interface as a parameter. public class Testing { public static void

More information

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 22 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12 ArrayLists COMP1400 Week 8 Working with arrays There are a number of common actions we want to do with arrays: adding and deleting copying looking for a particular element counting the elements Arrays

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

Examination Questions Midterm 1

Examination Questions Midterm 1 CS1102s Data Structures and Algorithms 10/2/2010 Examination Questions Midterm 1 This examination question booklet has 9 pages, including this cover page, and contains 15 questions. You have 40 minutes

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ ABSTRACT DATATYPES 2 Abstract Datatype (ADT)

More information

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II Adam Blank Lecture 5 Winter 2015 CSE 143 Computer Programming II CSE 143: Computer Programming II Stacks & Queues Questions From Last Time 1 Can we include implementation details in the inside comments

More information

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. 1. The Nose class... b) will not compile because the m1 method parameter should be named n, not x. 2. The Ears class...

More information

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units. This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units. Introduction Overview Advancements in technology are

More information

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011 1 ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES Lecture 4 CS 2110 Summer 2011 Lists are Iterable 4 for public static void printlist(list strings) { for (int idx = 0; idx < strings.size();

More information

Main loop structure. A Technical Support System. The exit condition. Main loop body

Main loop structure. A Technical Support System. The exit condition. Main loop body Main concepts to be covered More sophisticated behavior Using library classes Reading documentation Using library classes to implement some more advanced functionality 5.0 2 The Java class library Thousands

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList: Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Abstract Data Types and Data Structures

Abstract Data Types and Data Structures Unit 6, Part 1 Abstract Data Types and Data Structures Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Congrats on completing the first half! In the second half, we will study fundamental

More information

CS1083 Week 2: Arrays, ArrayList

CS1083 Week 2: Arrays, ArrayList CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08 Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics Multiple references to an array d o u b l e prices

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed

More information

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards

More information

Lecture 6: ArrayList Implementation

Lecture 6: ArrayList Implementation Lecture 6: ArrayList Implementation CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Programming Assignment Weak AI/Natural Language Processing: Generate text by building frequency lists based

More information

CMSC 202. Containers

CMSC 202. Containers CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.

More information