CMSC 202H. ArrayList, Multidimensional Arrays



Similar documents
Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

AP Computer Science Java Subset

Class 32: The Java Collections Framework

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Software Development with UML and Java 2 SDJ I2, Spring 2010

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Introduction to Data Structures

Data Structures and Algorithms

Arrays in Java. Working with Arrays

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Data Structures in the Java API

Basic Programming and PC Skills: Basic Programming and PC Skills:

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

D06 PROGRAMMING with JAVA

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Computer Programming I

Moving from CS 61A Scheme to CS 61B Java

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Arrays. Introduction. Chapter 7

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

AP Computer Science Java Mr. Clausen Program 9A, 9B

Introduction to Programming

The C Programming Language course syllabus associate level

C++ INTERVIEW QUESTIONS

Introduction to Programming System Design. CSCI 455x (4 Units)

5 Arrays and Pointers

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CS170 Lab 11 Abstract Data Types & Objects

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

Crash Course in Java

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

LINKED DATA STRUCTURES

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

D06 PROGRAMMING with JAVA

Sample CSE8A midterm Multiple Choice (circle one)

Contents. 9-1 Copyright (c) N. Afshartous

J a v a Quiz (Unit 3, Test 0 Practice)

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Tutorial: Getting Started

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

In this Chapter you ll learn:

Java Interview Questions and Answers

Introduction to Java. CS 3: Computer Programming in Java

Basic Object-Oriented Programming in Java

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Lecture J - Exceptions

Java from a C perspective. Plan

The Interface Concept

CmpSci 187: Programming with Data Structures Spring 2015

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

WRITING DATA TO A BINARY FILE

Fundamentals of Java Programming

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

The Java Collections Framework

Java (12 Weeks) Introduction to Java Programming Language

CS 111 Classes I 1. Software Organization View to this point:

CSC 551: Web Programming. Fall 2001

Inheritance, overloading and overriding

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Practical Session 4 Java Collections

Java Application Developer Certificate Program Competencies

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

Chapter 8: Bags and Sets

Semantic Analysis: Types and Type Checking

Building Java Programs

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Programming Languages CIS 443

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

AP Computer Science A 2004 Free-Response Questions

An Incomplete C++ Primer. University of Wyoming MA 5310

Lecture 5: Java Fundamentals III

Transcription:

CMSC 202H ArrayList, Multidimensional Arrays

What s an Array List ArrayList is a class in the standard Java libraries that can hold any type of object an object that can grow and shrink while your program is running (unlike arrays, which have a fixed length once they have been created) In general, an ArrayList serves the same purpose as an array, except that an ArrayList can change length while the program is running 9/2011 2

The ArrayList Class The class ArrayList is implemented using an array as a private instance variable When this hidden array is full, a new larger hidden array is created and the data is transferred to this new array 9/2011 3

Using the ArrayList Class In order to make use of the ArrayList class, it must first be imported import java.util.arraylist; An ArrayList is created and named in the same way as object of any class: ArrayList alist = new ArrayList(); (Note that what we are teaching here is an obsolete, simplified form of ArrayList you can use for now; for documentation, see: http://download.oracle.com/javase/1.4.2/docs/api/java/util/arraylist.html. Later, we will learn the proper form, after covering Generics.) 9/2011 4

Adding elements to an ArrayList The add method is used to add an element at the end of an ArrayList list.add("something"); The method name add is overloaded There is also a two argument version that allows an item to be added at any currently used index position or at the first unused position 9/2011 5

How many elements? The size method is used to find out how many indices already have elements in the ArrayList int howmany = list.size(); The set method is used to replace any existing element, and the get method is used to access the value of any existing element list.set(index, "something else"); String thing = (String) list.get(index); Note that the returned value must be cast to the proper type size is NOT capacity size is the number of elements currently stored in the ArrayList Capacity is the maximum number of elements which can be stored. Capacity will automatically increase as needed 9/2011 6

ArrayList code Example public static void main( String[ ] args) { ArrayList myints = new ArrayList(); System.out.println( Size of myints = + myints.size()); for (int k = 0; k < 10; k++) myints.add( 3 * k ); myints.set( 6, 44 ); System.out.println( Size of myints = + myints.size()); for (int k = 0; k < myints.size(); k++) System.out.print( myints.get( k ) +, ); } // output Size of myints = 0 Size of myints = 10 0, 3, 6, 9, 12, 15, 44, 21, 24, 27 9/2011 7

Methods in the Class ArrayList The tools for manipulating arrays consist only of the square brackets and the instance variable length ArrayLists, however, come with a selection of powerful methods that can do many of the things for which code would have to be written in order to do them using arrays 9/2011 8

ArrayList Constructors Constructors: ArrayList() Constructs an empty list with an initial capacity of ten. ArrayList(int initialcapacity) Constructs an empty list with the specified initial capacity. (Constructor and method descriptions borrowed from Sun javadoc pages) 9/2011 9

ArrayList Methods Method Summary (incomplete) void add(int index, Object element) Inserts the specified element at the specified position in this list. boolean add(object o) Appends the specified element to the end of this list. int size() Returns the number of elements in this list. 9/2011 10

ArrayList Methods (cont) Object set(int index, Object element) Replaces the element at the specified position in this list with the specified element. Object get(int index) Returns the element at the specified position in this list. Object remove(int index) Removes the element at the specified position in this list. protected void removerange(int fromindex, int toindex) Removes from this List all of the elements whose index is between fromindex, inclusive and toindex, exclusive. 9/2011 11

ArrayList Methods (cont) void clear() Removes all of the elements from this list. Object clone() Returns a shallow copy of this ArrayList instance. int indexof(object elem) Searches for the first occurence of the given argument, testing for equality using the equals method. int lastindexof(object elem) Returns the index of the last occurrence of the specified object in this list. 9/2011 12

The "For Each" Loop The ArrayList class is an example of a collection class Starting with version 5.0, Java has added a new kind of for loop called a for-each or enhanced for loop This kind of loop has been designed to cycle through all the elements in a collection (like an ArrayList) 9/2011 13

for-each example public class ForEach { public static void main(string[ ] args) { ArrayList list = new ArrayList(); list.add(new Date(1, 1, 1000)); list.add(new Date(7, 4, 1776)); list.add(new Date(9, 1, 2011)); // for each object, i, in list for( Object i : list ) System.out.println( i ); } } //-- Output --- 1/1/1000 7/4/1776 9/1/2011 9/2011 14

Copying an ArrayList // create an ArrayList of Dates (assume we have some around) ArrayList a = new ArrayList( ); a.add(d1); a.add(d2); a.add(d3); Assignment doesn t work As we ve seen with any object, using assignment just makes two variables refer to the same ArrayList. ArrayList b = a; a b 1/1/1000 7/4/1776 9/1/2011 Stack Heap 9/2011 16

Copying an ArrayList ArrayList s clone( ) method makes a shallow copy ArrayList b = a.clone( ); a 1/1/1000 7/4/1776 9/1/2011 b Stack Heap 9/2011 17

Copying an ArrayList We need to manually make a deep copy ArrayList b = a.clone( ); 1/1/1000 7/4/1776 9/1/2011 a b Stack Heap 9/2011 18

Copying an ArrayList We need to manually make a deep copy ArrayList b = a.clone( ); for( int k = 0; k < b.size( ); k++) { } Date origdate = (Date) b.get(k); b.set(k, new Date(origDate)); 1/1/1000 7/4/1776 9/1/2011 a 1/1/1000 7/4/1776 9/1/2011 b Stack Heap 9/2011 19

ArrayList vs Array Why use an array instead of an ArrayList 1. An ArrayList is less efficient than an array 2. ArrayList does not have the convenient square bracket notation 3. The elements of an ArrayList must be a class type (or other reference type). It cannot be a primitive type. (Although wrappers, auto boxing, and auto unboxing make this less of an issue with Java 5) 9/2011 20

ArrayList vs Array Why use an ArrayList instead of an array? 1. Arrays can t grow. Their size is fixed at compile time. ArrayList grows and shrinks as needed while your program is running 2. You need to keep track of the actual number of elements in your array (recall partially filled arrays). ArrayList will do that for you. 3. Arrays have no methods (just length instance variable) ArrayList has powerful methods for manipulating the objects within it 9/2011 21

Some Warnings This lecture describes an obsolete form of ArrayList The original form of ArrayList stored Object elements, so you had to constantly do casts The addition of generics to the language completely changed the use of collections like ArrayLists To keep a modicum of backwards compatibility, raw types allow ArrayLists to be used as originally designed Important: just because you can mix types together does not mean you should! 9/2011 22

The Vector Class The Java standard libraries have a class named Vector that behaves almost exactly the same as the class ArrayList In most situations, either class could be used, however the ArrayList class is newer (Java 5), and is becoming the preferred class 9/2011 23

Multidimensional Arrays 9/2011 24

Multidimensional Arrays Review of 1-dimensional arrays: To declare and initialize: int[] myarray = new int[4]; To access: myarray[3] = myarray[3] + 1; To use as an object: for (i = 0; I < myarray.length; i++) { To demonstrate that it s a reference variable: myarray = null; // Now, myarray[3] would cause an error 9/2011 25

Multidimensional Arrays Extending to 2-dimensional arrays: To declare and initialize: int[][] myarray = new int[3][4]; // How would you declare 2-dim arrays in C? To access: myarray[1][3] = myarray[1][3] + 1; To use as an object: numrows = myarray.length; // Following assumes rectangular matrix numcols = myarray[0].length; 9/2011 26

Multidimensional Arrays But in Java, a 2D array is actually a referenceto-an-array-of-references: // Can do: myarray[1] = null; myarray[1][3] = 47; // This will cause error // but myarray[0][3] still okay // Can also make it a ragged array: myarray[1] = new int[20]; // What do you think following does? myarray = new int[10][]; // and what would this do? myarray = new int[40]; 9/2011 27

Multidimensional Arrays Luckily, if you don t want to get fancy, you can pretend that it s simply a 2-D array Even if you do create complex, dynamically allocated, ragged arrays, you don t have to worry about memory management 9/2011 28