11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 1 The Study of Body Function Image PowerPoint
Introduction to Computation and Problem
19 Copyright © 2005, Oracle. All rights reserved. Distributing Modular Applications: Developing Web Services.
7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
12 Copyright © 2005, Oracle. All rights reserved. Structuring Code Using Abstract Classes and Interfaces.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
11 Copyright © 2005, Oracle. All rights reserved. Creating the Business Tier: Enterprise JavaBeans.
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
8 Copyright © 2005, Oracle. All rights reserved. Object Life Cycle and Inner Classes.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
6 Copyright © 2005, Oracle. All rights reserved. Building Applications with Oracle JDeveloper 10g.
17 Copyright © 2005, Oracle. All rights reserved. Deploying Applications by Using Java Web Start.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Title Subtitle.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lecture 15 Linked Lists part 2
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 10 Arrays and Tile Mapping Starting Out with Games & Graphics.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Building Java Programs Chapter 10
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
List Implementations That Use Arrays
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
ITEC200 Week04 Lists and the Collection Interface.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
1 CSE1301 Computer Programming: Lecture 27 List Manipulation.
Data Structures Using C++
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 11: Linked Lists Lecturer: Santokh Singh Assignment 2 due tomorrow, i.e. Friday 21 Jan 2005.
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Double-Linked Lists and Circular Lists
John Hurley Cal State LA
1 Joe Meehean. Ordered collection of items Not necessarily sorted 0-index (first item is item 0) Abstraction 2 Item 0 Item 1 Item 2 … Item N.
ABC Technology Project
1 Designing Hash Tables Sections 5.3, 5.4, Designing a hash table 1.Hash function: establishing a key with an indexed location in a hash table.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Object Oriented Programming with Java
Page 1 – Spring 2010Steffen Vissing Andersen Software Development with UML and Java 2 SDJ I2, Spring 2010 Agenda – week 7, 2010 • Pakages • Looking back.
Review Pseudo Code Basic elements of Pseudo code
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
The List ADT Textbook Sections
© 2012 National Heart Foundation of Australia. Slide 2.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Based on slides from Deitel & Associates, Inc.
25 seconds left…...
We will resume in: 25 Minutes.
Pointers and Arrays Chapter 12
Chapter 11 Component-Level Design
Chapter 14 Introduction to Collections
Abstract Class, Packages and interface from Chapter 9
1 Abstract Class and Packages from Chapter 9 Lecture.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
111 © 2002, Cisco Systems, Inc. All rights reserved.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Collections Dwight Deugo Nesa Matic
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Object Oriented Programming in java
Presentation transcript:

11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections

11-2 Copyright © 2005, Oracle. All rights reserved. Objectives After completing this lesson, you should be able to do the following: Describe how to create arrays of primitives and objects Process command-line variables Work with vectors Explore other Java collections such as Enumerators, Iterators, ArrayLists, and Hashtables Process command-line and system properties

11-3 Copyright © 2005, Oracle. All rights reserved. What Is an Array? An array is a collection of variables of the same type. Each element can hold a single item. Items can be primitives or object references. The length of the array is fixed when it is created [0] [1] [2] [3] Action Comedy Drama [0] [1] [2]

11-4 Copyright © 2005, Oracle. All rights reserved. Creating an Array of Primitives 1.Declare the array: type is a primitive, such as int and so on. 2.Create the array object: 3. Initialize the array elements (optional). Null arrayName type[] arrayName; … or … type arrayName[]; // Create array object syntax arrayName = new type[size];

11-5 Copyright © 2005, Oracle. All rights reserved. Declaring an Array of Primitives Create a variable to reference the array object: When an array variable is declared: –Its instance variable is initialized to null until the array object has been created –Its method variable is unknown until the object is created int[] powers; // Example null powers

11-6 Copyright © 2005, Oracle. All rights reserved. Creating an Array Object for an Array of Primitives Create an array of the required length and assign it to the array variable: –The array object is created by using the new operator. The contents of an array of primitives are initialized automatically. int[] powers;// Declare array variable powers = new int[4];//Create array object powers

11-7 Copyright © 2005, Oracle. All rights reserved. Notes Page

11-8 Copyright © 2005, Oracle. All rights reserved. Initializing Array Elements Assign values to individual elements: Create and initialize arrays at the same time: int[] primes = {2, 3, 5, 7}; type[] arrayName = {valueList}; primes [0] [1] [2] [3] arrayName[index] = value; powers[0] = 1; powers [0] [1] [2] [3]

11-9 Copyright © 2005, Oracle. All rights reserved. Creating an Array of Object References 1.Declare the array: 2.Create the array object: 3.Initialize the objects in the array. null arrVar null arrVar Action Comedy Drama arrVar ClassName[] arrVar; … or … ClassName arrVar[]; // Create array object syntax arrVar = new ClassName[size];

11-10 Copyright © 2005, Oracle. All rights reserved. Initializing the Objects in the Array Assign a value to each array element: Create and initialize the array at the same time: String[] categories = {"Action", "Comedy", "Drama"}; // Create an array of four empty Strings String[] arr = new String[4]; for (int i = 0; i < arr.length; i++) { arr[i] = new String(); }

11-11 Copyright © 2005, Oracle. All rights reserved. Using an Array of Object References Any element can be assigned to an object of the correct type: Each element can be treated as an individual object: An array element can be passed to any method; array elements are passed by reference. System.out.println ("Length is " + categories[2].length()); String category = categories[0];

11-12 Copyright © 2005, Oracle. All rights reserved. Arrays and Exceptions ArrayIndexOutOfBoundsException occurs when an array index is invalid: NullPointerException occurs when you try to access an element that has not been initialized: Movie[] movieList = new Movie[3]; // The following will throw NullPointerException String director = movieList[0].getDirector(); String[] list = new String[4]; //The following throws ArrayIndexOutOfBoundsException System.out.println(list[4]);

11-13 Copyright © 2005, Oracle. All rights reserved. Multidimensional Arrays Java supports arrays of arrays: type[][] arrayname = new type[n1][n2]; int[][] mdarr = new int[4][2]; mdarr[0][0] = 1; mdarr[0][1] = 7; [0] [1] [2] [3] mdarr [0][0] [0][1]

11-14 Copyright © 2005, Oracle. All rights reserved. main() Revisited main() has a single parameter, args. args is an array of Strings that holds command- line parameters: public class SayHello { public static void main(String[] args) { if (args.length != 2) System.out.println("Specify 2 arguments"); else System.out.println(args[0]+" "+args[1]); } … C:\> java SayHello Hello World

11-15 Copyright © 2005, Oracle. All rights reserved. Working with Variable-Length Structures The Vector class implements a resizable array of any type of object: Creating an empty vector: Creating a vector with an initial size: Vector members = new Vector(); // Create a vector with 10 elements. The vector // can be expanded later. Vector members = new Vector(10);

11-16 Copyright © 2005, Oracle. All rights reserved. Modifying a Vector Add an element to the end of the vector: Add an element at a specific position: Remove the element at a specific index: String name = MyMovie.getNextName(); members.addElement(name); // Remove the first element members.removeElementAt(0); // Insert a string at the beginning members.insertElementAt(name, 0);

11-17 Copyright © 2005, Oracle. All rights reserved. Accessing a Vector Get the first element: Get an element at a specific position: Find an object in a vector: Get the size of a vector: String s = (String)members.firstElement(); int size = members.size(); String s = (String)members.elementAt(2); int position = members.indexOf(name);

11-18 Copyright © 2005, Oracle. All rights reserved. Java Collections Framework Java Collections Framework is an API architecture for managing a group of objects that can be manipulated independently of their internal implementation. It is: Found in the java.util package Defined by six core interfaces and some implementation classes: – Collection interface: Generic group of elements – Set interface: Group of unique elements – List interface: Ordered group of elements – Map interface: Group of unique keys and their values – SortedSet and SortedMap for a sorted Set and Map

11-19 Copyright © 2005, Oracle. All rights reserved. Notes Page

11-20 Copyright © 2005, Oracle. All rights reserved. Collections Framework Components Collections Framework is a set of interfaces and classes used to store and manipulate groups of data as a single unit. Core Interfaces are the interfaces used to manipulate collections, and to pass them from one method to another. Implementations are the actual data objects used to store collections, which implement the core collection interface. Algorithms are pieces of reusable functionality provided by the JDK.

11-21 Copyright © 2005, Oracle. All rights reserved. Using ArrayList and Hashtable The ArrayList class: Is a resizable implementation of the List interface Allows manipulation of the array size Has capacity that grows as elements are added to the list The Hashtable class: Is a legacy class similar to Map implementations Is used to store arbitrary objects that are indexed by another arbitrary object Is commonly used with String as the key to store objects as values

11-22 Copyright © 2005, Oracle. All rights reserved. Using Iterators The Iterator interface, which is part of Java Collection Framework, can be used to process a series of Objects. The java.util.Iterator interface: Implements an object-oriented approach for accessing elements in a collection Replaces the java.util.Enumeration approach Contains the following methods: – hasNext() returns true if more elements exist. – next() returns the next Object, if any. – remove() removes the last element returned.

11-23 Copyright © 2005, Oracle. All rights reserved. Summary In this lesson, you should have learned how to: Create Java arrays of primitives Create arrays of object references Initialize arrays of primitives or object references Process command-line arguments in the main() method Use the Vector object to implement resizable arrays Use ArrayList and Hashtable classes

11-24 Copyright © 2005, Oracle. All rights reserved. Practice 11: Overview This practice covers: Modifying the DataMan class –Create an array to hold the Customer, Company, and Individual objects. –Add a method to ensure that the array is successfully created and initialized. –Add a method to find a customer by an ID value.

11-25 Copyright © 2005, Oracle. All rights reserved. Notes Page for Practice 11

11-26 Copyright © 2005, Oracle. All rights reserved. Practice 11: Notes

11-27 Copyright © 2005, Oracle. All rights reserved. Practice 11: Notes

11-28 Copyright © 2005, Oracle. All rights reserved. Practice 11: Notes