Arrays in Java What, why and how Copyright 1998-2011 Curt Hill.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 9 Introduction to Arrays
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Lists in Python.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
Statement Level Flow of Control Iteration Structures Copyright © by Curt Hill.
Copyright © – Curt Hill Pointers A Light Introduction.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
Copyright Curt Hill Arrays in C/C++ What? Why? How?
Copyright Curt Hill Arrays in C/C++ More on usage.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
Copyright © Curt Hill Simple I/O Input and Output using the System and Scanner Objects.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
The for Statement A most versatile loop
Arrays Chapter 7.
Sorting Mr. Jacobs.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Array in C# Array in C# RIHS Arshad Khan
Sections 10.1 – 10.4 Introduction to Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
4. Java language basics: Function
User-Written Functions
Arrays 2/4 By Pius Nyaanga.
The for-each or for-all loop introduced in Java 5
Chapter 7 Part 1 Edited by JJ Shepherd
Java Review: Reference Types
Arrays, For loop While loop Do while loop
A brief look at some of the new features introduced to the language
Object Oriented Programming COP3330 / CGS5409
Multiple Dimension Arrays
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
The most important decision statement
Declaration, assignment & accessing
Lecture 18 Arrays and Pointer Arithmetic
Object Oriented Programming in java
Compound Statements A Quick Overview
A Robust Data Structure
Other displays Saving Arrays Using fors to process
Methods Again Parameter Passage
The Java switch Statement
7 Arrays.
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
Peer Instruction 4 Control Loops.
Arrays.
Arrays 2-May-19.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Classes and Objects Object Creation
Java Coding 6 David Davenport Computer Eng. Dept.,
SPL – PS2 C++ Memory Handling.
Putting Values into a Suitable Form for Display
While and Do While Syntax, semantics and examples
Presentation transcript:

Arrays in Java What, why and how Copyright 1998-2011 Curt Hill

What is an array? Multiple occurrences of values of one type One name many values Item is selected at run time by an integer index A true data type in Java, unlike C++ Always an object Always dynamic The mark of arrays is a pair of square brackets: [ ] Copyright 1998-2011 Curt Hill

Why do we need arrays? We often need to select a value by an index rather than just name If a picture has 240,000 pixels, do we really want 240,000 different variable names? Instead we find one name and use an integer subscript to choose which of the many we want Copyright 1998-2011 Curt Hill

Counting For Example static void process(Picture p){ // Enhance red Pixel [] pixels = p.getPixels(); for(int i=0;i<pixels.length;i++){ Pixel ap = pixels[i]; int r = 3 *ap.getRed()/2; ap.setRed(r); } Copyright 1998-2011 Curt Hill

Explanation A reference to pixels either refers to the whole object: Such as pixels.length which describes how many Otherwise a bracket selects which one: pixels[i].setRed(red); Set the ith pixel’s red value Copyright 1998-2011 Curt Hill

For All Example static void process(Picture p){ // Enhance red Pixel [] pixels = p.getPixels(); for(Pixel ap: pixels){ int r = 3 * ap.getRed()/2; ap.setRed(r); } Copyright 1998-2011 Curt Hill

Explanation This version of the for does two things for us It infers the length of the array It hides the subscripting of the pixel Copyright 1998-2011 Curt Hill

Arrays One name, many values Arrays elements demonstrate identical form and function The form is that each element has exactly the same type Polymorphism can come into play here, but not considered further until much later The function is that they are there for the same purpose Copyright 1998-2011 Curt Hill

What is needed? Declaration Allocation Access and reference Marked by the [] Allocation Determines the size Access and reference Indexing or subscripting Answers to these questions: What can we do to an array element? What can we do to the whole array? Copyright 1998-2011 Curt Hill

Array declaration Two similar declarations: int [ ] a, b, c[ ]; int d[]; Brackets may precede or follow the variable name No size is allowed in declaration Brackets are attached to variable name b is not an array, but a simple integer Even an array of primitives is an object Copyright 1998-2011 Curt Hill

Array Allocation Two step for objects or primitives Allocate the array handle This determines the size of the array Allocate (or initialize) the individual elements Primitives need to be initialized Objects are usualy initialized by the allocation In either case, usually done with a for Copyright 1998-2011 Curt Hill

Preface to Allocation At least for a time we will get an array from somewhere else A picture We will not use the new operator on it, nor will we initialize it by accessing individual elements We can create and allocate arrays with new The technique is seen in next slides Copyright 1998-2011 Curt Hill

Allocation examples Two statements One statement int x[]; x = new int [20]; One statement int a[] = new int[20]; The initialization of both of these still needs to be done Copyright 1998-2011 Curt Hill

Using whole arrays Suppose the following declaration int [] a = new int [5], b[]; Without subscript an array name is just an object handle b = a; Have both handles refer to same array a b Copyright 1998-2011 Curt Hill

Subscripting Using a subscript an element is obtained a[k] = a[j+2]-2; Anywhere an int can be used a[k] can be used First element has subscript zero Last element has subscript size minus one Copyright 1998-2011 Curt Hill

A Subscript The item in brackets chooses which element of array to be used The item may be a integral constant integral variable integral expression No doubles or float subscripts There is no element between [2] and [3] Must be in the correct range 0 to length of array-1 Copyright 1998-2011 Curt Hill

Subscript Errors Suppose: int [] a = new int [10]; . . . a[k] = 2; If k is less than zero or greater than 9 a subscript error occurs ArrayIndexOutOfBoundsException is thrown It is the programmers responsibility to guarantee that an index is in the correct bounds Copyright 1998-2011 Curt Hill

Subscript Traceback Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2 at pd1.PictureDemo1.process(PictureDemo1.java:23) at pd1.PictureDemo1.main(PictureDemo1.java:16) ArrayIndexOut OfBounds is the error The -2 is the actual subscript Find the first (from the top) line that is in your code. In this case it is line 23 Copyright 1998-2011 Curt Hill

Discussion Since an array is one name with many values, an array element has a two piece name The array name and the subscript We may assign to this name or use in an expression Processing an array sequentially is most often done with a for statement Copyright 1998-2011 Curt Hill

Array extras Arrays can be parameters or results of methods Lowest subscript is always zero The number of elements of an array can be accessed by a property: a.length One larger than largest valid subscript Copyright 1998-2011 Curt Hill

The questions What can we do to an array element? Anything reasonable to do to a variable of the same type What can we do to the whole array? Pass as a parameter Return as a result Assign the handle Get the length Copyright 1998-2011 Curt Hill

Array Handles Like any object what you have is the handle This handle can be reused int [] ar = new int[20]; … ar = new int[40]; Thus the length of the array is dependent on the current version A different length depending on where it is checked Copyright 1998-2011 Curt Hill

Tracing Somewhat problematic Since one name has many values we have to be careful to keep track of them properly Moreover, we do not know how many elements there are until the allocation Copyright 1998-2011 Curt Hill

Discussion A primitive passed to a method just passes a copy The original cannot be changed An object just passes a handle The object may changed but not the handle Arrays may thus have their values changed Strings are the exception The string is immutable Copyright 1998-2011 Curt Hill

Conclusions Arrays are a valuable means to structure data They are an object without an object name They require a subscript (or index) to access individual elements Methods may change array parameters Multiple dimension arrays are also possible but will be discussed later Copyright 1998-2011 Curt Hill