ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014 1.

Slides:



Advertisements
Similar presentations
Arrays I Savitch Chapter 6.1: Introduction to Arrays.
Advertisements

Generics and the ArrayList Class
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Arrays part 3 Multidimensional arrays, odds & ends.
Arrays Chapter 6 Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
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.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
ArrayList, Multidimensional Arrays
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CSE 1201 Object Oriented Programming ArrayList 1.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
Array, Strings and Vectors
Chapter 8 Slides from GaddisText
CMSC 202 ArrayList Aug 9, 2007.
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Arrays.
Presentation transcript:

ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall

Introduction to Arrays An array is an object used to store a (possibly large) collection of data. All the data stored in the array must be of the same type. An array object has a small number of predefined methods. 2

Introduction to Arrays, cont. Sometimes you want to know several things about a collection of data: –the average –the number of items below the average –the number of items above the average –etc. This requires all the items to be stored as variables of one kind or another. 3

ARRAYS You can make an array of any type – int, double, String All elements of an array must have the same type 1.int[] values = new int[5]; 2.int[] values = { 12, 24, -23, 47 }; values[1] = ? values[length] = ? int length = values.length; // not lenght !!! 4

Array Details Syntax for creating an array Base_Type[] Array_Name = new Base_Type[Length]; Arrays of primitive types or complex types Example int[] pressure = new int[100]; or int[] pressure; pressure = new int[100]; 5

Indices and length The indices of an array start with 0 and end with Array_Name.length-1. When a for loop is used to step through an array, the loop control variable should start at 0 and end at length-1. Example for (lcv = 0; lcv < temperature.length; index++) 6

Initializing Arrays An array can be initialized at the time it is declared. example double[] reading = {3,3, 15.8, 9.7}; –The size of the array is determined by the number of values in the initializer list. 7

Arguments for the Method main Recall the heading for method main : public static void main(String[] args) Method main takes an array of String values as its argument. A default array of String values is when you run a program. 8

Arguments for the Method main, cont. Alternatively, an array of String values can be provided in the command line. Example java TestProgram Mary Lou – args[0] is set to “Mary” – args[1] is set to “Lou” System.out.println(“Hello “ + args[0] + “ “ + args[1]); prints Hello Mary Lou. 9

Use of = and == with Arrays The assignment operator ‘ = ‘and the equality operator ‘ == ’, when used with arrays, behave the same as when used with other objects. –The assignment operator creates an alias, not a copy of the array. –The equality operator determines if two references contain the same memory address, not if two arrays contain the same values. 10

Making a Copy of an Array 1.way int[] a = new int[50]; int[] b = new int[50];... for (int j = 0; j < a.length; j++) b[j] = a[j]; 2.way Clone() b = a.clone(); 11

Determining the “Equality” of Two Arrays, cont. A while loop can be used. –A boolean variable match is set to true. –Each element in the first array is compared to the corresponding element in the second array. –If two elements are different, match is set to false and the while loop is exited. –Otherwise, the loop terminates with match still set to true. 12

Sorting Arrays Sometime we want numbers in an array sorted from smallest to largest, or from largest to smallest. Sometimes we want the strings referenced by an array to be in alphabetical order. Sorting techniques typically are easy to adapt to sort any type that can be ordered. 13

Selection Sort, cont. Selection sort begins by finding a smallest item in the array and swapping it with the item in a[0]. Selection sort continue by finding a smallest item in the remainder of the array and swapping it with the next item in array a. Selection sort terminates when only one item remains. 14

Selection Sort, cont. 15

Swapping Elements To swap two elements a[i] and a[j], one of them must be saved temporarily. 16

Swapping Elements, cont. class interchange 17

Introduction to Multidimensional Arrays An array with more than one index sometimes is useful. example: savings account balances at various interest rates for various numbers of years –columns for interest rates –rows for years This two-dimensional table calls for a two- dimensional array. 18

Introduction to Multidimensional Arrays, cont. 19

Multidimensional-Array Basics example declaration int[][] table = new int [10][6]; or int[][] table; table = new int[10][6]; The number of bracket pairs in the declaration is the same as the number of indices. 20

Multidimensional-Array Basics, cont. Syntax Base_Type[]…[] Array_Name = new Base_Type[Length_1]…[Length_n]; Examples char[][] page = new char [100][80]; double[][][] threeDPicture = new double[10][20][30]; SomeClass[][] entry = new SomeClass[100][80]; 21

Multidimensional-Array Basics, cont. Nested for loops can be used to set the values of the elements of the array and to print the values of the elements of the array. 22

2-dim Arrays int [][] test = new int [][]; – Error: Array dimension is missing int [][] test = new int [3][]; – Raw number is 3, but column number is not defined yet – System.out.println(test.length); // 3 – test = new int [3][2]; – System.out.println(test[1].length); // 2 23

Ragged Arrays Since a two-dimensional array in Java is an array of arrays, each row can have a different number of elements (columns). Arrays in which rows have different numbers of elements are called ragged arrays. 24

Ragged Arrays, cont. Example int[][] b = new int[3][]; b[0] = new int[5]; b[1] = new int[7]; b[2] = new int[4]; 25

A Weakness of Arrays Suppose we declare an array of “Student” objects: Student[] students = new Student[10]; What if a new student joins the class? The size of an array cannot be increased after it is instantiated 26

Resizing an Array (the hard way) Student[] students = new Student[10]; // do some stuff… // now we need to add student 11 Student[] students2 = new Student[11]; for(int i = 0; i < students.length; i++) { students2[i] = students[i]; } students2[10] = new Student(); 27

An Alternative to Arrays -ArrayList Class- ArrayList – No need to pre-define the size ArrayList list = new ArrayList(); list.add("a"); for (int i = 0; i < list.size(); i++) { System.out.println("----- "+list.get(i)); } 28

An Alternative to Arrays - Vector Class- The class Vector can be used to implement a list, replacing a simple array The size of a Vector object can grow/shrink during program execution The Vector will automatically grow to accommodate the number of elements you put in it 29

class Vector (continued) The class Vector is contained in the package java.util Programs must include either: – import java.util.*; – import java.util.Vector; 30

Vector Declaration Declare/initialize Vector students = new Vector (); The syntax is used to declare the type of object that will be stored in the Vector If you add a different type of object, an exception is thrown Not strictly necessary, but highly recommended (compiler warning) 31

Vector Size/Capacity The size of a vector is the number of elements The capacity of a vector is the maximum number of elements before more memory is needed If size exceeds capacity when adding an element, the capacity is automatically increased – Declares a larger storage array – Copies existing elements, if necessary – Growing the capacity is expensive! By default, the capacity doubles each time 32

Setting Initial Capacity If you know you will need a large vector, it may be faster to set the initial capacity to something large Vector students = new Vector (1000); 33

Size and capacity Get the current size and capacity: Vector students = new Vector (1000); students.size(); // returns 0 students.capacity(); // returns 1000 Setting size and capacity: // adds null elements or deletes elements if necessary students.setSize(10); // increases capacity if necessary students.ensureCapacity(10000); 34

Vector stringList = new Vector (); stringList.add("Spring"); stringList.add("Summer"); stringList.addElement("Fall"); stringList.addElement("Winter"); Adding Elements add and addElement have identical functionality 35

stringList.get(0); // “Spring” stringList.get(3); // “Winter” stringList.get(4); // ArrayIndexOutOfBounds Exception Accessing Elements 36