Comp1004: Loops and Arrays II

Slides:



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

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
ArrayLists.  The Java API includes a class named ArrayList. The introduction to the ArrayList class in the Java API documentation is shown below.  java.lang.Object.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
Chapter 11 Arrays Continued
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.
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.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
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.
ArrayList By Neil Butcher. What is the difference between an ArrayList and an Array? An ArrayList is in many ways similar to an array, but has a few subtle.
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.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
List Interface and Linked List Mrs. Furman March 25, 2010.
The ArrayList Data Structure Standard Arrays at High Speed!
Chapter 9 Introduction to Arrays Fundamentals of Java.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Comp1004: Conclusions Revision Session. Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some.
Comp1004: Loops and Arrays I Whiles, For and Arrays[]
New Java Features Advanced Programming Techniques.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
Sixth Lecture ArrayList Abstract Class and Interface
EECE 310: Software Engineering
(like an array on steroids)
Lecture 5 D&D Chapter 6 Arrays and ArrayLists Date.
John Hurley Cal State LA
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
ADT’s, Collections/Generics and Iterators
Intro to Collections.
Data Structures 1 1.
Java Generics.
HW-6 Deadline Extended to April 27th
Array List Pepper.
The ArrayList Class An ArrayList is a complex data structure that allows you to add or remove objects from a list and it changes size automatically. The.
Can store many of the same kind of data together
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generics 27-Nov-18.
Arrays versus ArrayList
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
Java Programming Arrays
CS2013 Lecture 4 John Hurley Cal State LA.
Can store many of the same kind of data together
Arrays and Collections
Coding Concepts (Basics)
CMSC 202 ArrayList Aug 9, 2007.
CSC 221: Computer Programming I Fall 2009
Fall 2018 CISC124 2/22/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. The prof. (me!) will start grading the quiz.
ArrayLists 22-Feb-19.
Collections and iterators
Can store many of the same kind of data together
Review of Previous Lesson
Java Programming Language
slides created by Alyssa Harding
Creating and Modifying Text part 3
Review: libraries and packages
Generics 2-May-19.
Collections and iterators
Arrays and ArrayLists.
Arrays.
Why not just use Arrays? Java ArrayLists.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Comp1004: Loops and Arrays II Collections and Iterators

Coming Up Arrays vs. ArrayLists A Brief Introduction to Generics Declaration Insertion Access Removal A Brief Introduction to Generics Autoboxing and unboxing Iterator objects

Arrays vs. ArrayLists

Problems with Arrays They don’t change size It’s a pain adding new elements if you don’t know how many are there already You have to use indexes ArrayIndexOutOfBoundsException

ArrayList to the rescue! Arrays are built into the Java language (a bit like primitives) But Java also have a library of helpful classes you can use for free These are not part of the language, but are included with every JVM ArrayList is one of these library classes

Array vs ArrayList Array ArrayList

Changes size as you add elements Array vs ArrayList Array ArrayList They don’t change size Changes size as you add elements

Array vs ArrayList Array ArrayList They don’t change size Changes size as you add elements It’s a pain adding new elements if you don’t know how many are there already ArrayList has an add() method and takes care of its size itself

Array vs ArrayList Array ArrayList They don’t change size Changes size as you add elements It’s a pain adding new elements if you don’t know how many are there already ArrayList has an add() method and takes care of its size itself You have to use indexes You can use indexes if you want, but you don’t have to

Array vs ArrayList Array ArrayList They don’t change size Changes size as you add elements It’s a pain adding new elements if you don’t know how many are there already ArrayList has an add() method and takes care of its size itself You have to use indexes You can use indexes if you want, but you don’t have to ArrayIndexOutOfBoundsException Still thrown by ArrayList. Hey, it’s a fact of life, okay?

Array vs ArrayList Array ArrayList Declaration Insertion Access Removal 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);

ArrayList Advantages Arrays are useful for simple small tasks ArrayLists are better for more complex tasks They grow and shrink when you add and remove things – arrays are fixed size They have many useful methods... Check out the API: Application Programming Interface http://download.oracle.com/javase/6/docs/api/ type ‘java api’ into google

Here’s a bit of the method summary for ArrayList...

Brief Introduction to Generics

Spot the Problem… 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(); }

Spot the Problem… ArrayLists store objects of any type 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(); } 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!

Spot the Problem… ArrayLists store objects of any type 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(); } 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

Solving the Problem… 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(); }

Solving the Problem… 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++) { if(kennel.get(i) instanceof Dog) { Dog d = (Dog)kennel.get(i); d.bark(); } One option is to test what is in there using instanceof, and if it’s a Dog we can tell the compiler. This is called typecasting

Solving the Problem… 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++) { if(kennel.get(i) instanceof Dog) { Dog d = (Dog)kennel.get(i); d.bark(); } One option is to test what is in there using instanceof, and if it’s a Dog we can tell the compiler. This is called typecasting Makes my inner software engineer cringe! instanceof is a tool of last resort. If you’ve had to use it it probably means you’re program is not designed particularly well.

Solving the Problem… 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

Solving the Problem… ArrayList<Dog> kennel = new ArrayList<Dog>(); 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

A Note About Primitives ArrayLists (and other collections in the API) can only store objects. This means that when you want to store primitives you need to use wrapper objects. This is a pain :-( ArrayList<Integer> numStore; numStore = new ArrayList<Integer>(); numStore.add(new Integer(3)); numStore.add(new Integer(5)); numStore.add(new Integer(2)); int total = 0; for(int i = 0; i < numStore.size(); i++) { total = total + numStore.get(i).intValue(); } System.out.println(“Total is ” + total);

A Note About Primitives ArrayLists (and other collections in the API) can only store objects. This means that when you want to store primitives you need to use wrapper objects. This is a pain :-( ArrayList<Integer> numStore; numStore = new ArrayList<Integer>(); numStore.add(3); numStore.add(5); numStore.add(2); int total = 0; for(int i = 0; i < numStore.size(); i++) { total = total + numStore.get(i); } System.out.println(“Total is ” + total); Java 5 introduced autoboxing, a process where primitives are automatically cast to a wrapper where necessary. And unboxing, where they can be cast back again too

Iterators

Design Patterns In Programming a neat and elegant way of solving a problem is sometimes called a design pattern The Java API uses a number of well-known design patterns Including the use of iterators to help you iterate over a collection

Back at the Kennel… In our kennel example we used a for loop to iterate over the array ArrayList<Dog> kennel = new ArrayList<Dog>(); 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(); }

Back at the Kennel… In our kennel example we used a for loop to iterate over the array ArrayList<Dog> kennel = new ArrayList<Dog>(); 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<Dog> it = kennel.iterator(); while(it.hasNext()) { it.next().bark(); We could instead use an iterator object. Iterators are generic classes (like the ArrayList) and track our progress through a collection. We can use hasNext to see if there are more elements And next to get the next element (the iterator will automatically move to the next element).

Why are Iterators a useful pattern? ArrayList<Dog> kennel = new ArrayList<Dog>(); 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<Dog> it = kennel.iterator(); while(it.hasNext()) { it.next().bark();

Why are Iterators a useful pattern? ArrayList<Dog> kennel = new ArrayList<Dog>(); 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<Dog> 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!

Why are Iterators a useful pattern? public void makeThemBark(Iterator<Dog> 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!

Summary Arrays vs. ArrayLists A Brief Introduction to Generics Declaration Insertion Access Removal A Brief Introduction to Generics Autoboxing and unboxing Iterator objects