Fifth Lecture Arrays and Lists

Slides:



Advertisements
Similar presentations
1 Arrays, Strings and Collections [1] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
Advertisements

Introduction to C Programming
Arrays in JAVA CS 340 Software Design Muhammad Talha.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
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.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Lecture # 4. * An array is a group of contiguous or related data items that share a common name. * Each value is stored at a specific position * Position.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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.
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.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Lecture 07. Do not have to create an array while declaring array variable [] variable_name; int [] prime; int prime[]; Both syntaxes are equivalent No.
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.
1 Unit-2 Arrays, Strings and Collections. 2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Arrays Chapter 7.
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
Arrays Chapter 7.
Chapter 7 User-Defined Methods.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
Arrays in JAVA Visit for more Learning Resources.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Computer Programming BCT 1113
Lecture 5 D&D Chapter 6 Arrays and ArrayLists Date.
Array, Strings and Vectors
Chapter 7 Part 1 Edited by JJ Shepherd
A simple way to organize data
Arrays in C.
Object Oriented Programming
Java How to Program, Late Objects Version, 10/e
Polymorphism.
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.
EKT150 : Computer Programming
Review of Arrays and Pointers
Introduction To Programming Information Technology , 1’st Semester
Object Oriented Programming in java
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
MSIS 655 Advanced Business Applications Programming
Data Structures (CS212D) Week # 2: Arrays.
Arrays Chapter 7.
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
Arrays Week 2.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Java Programming Language
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Outline Creating Objects The String Class The Random and Math Classes
C++ Array 1.
How do you do the following?
Arrays.
Presentation transcript:

Fifth Lecture Arrays and Lists

Wrapper Classes As pointed out earlier, collections cannot handle basic data types such as int, float. They can converted into object types by using the wrapper classes supported by java.lang package. Basic Type Wrapper Class boolean Boolean char Character int Integer long Long float Float double Double

Methods in Wrapper Classes Constructors: Integer intVal = new Integer(i); Float floatVal = new Float(f); Converting objects to basic values int i = intVal.intValue(); float f = floatValue.floatValue(); Converting Numbers to Strings str = Integer.toString(i) str = Float.toStrin(f);

Methods in Wrapper Classes String Objects to Numeric Objectrs Integer intVal = Integer.ValueOf(str); Float floatVal = Float.ValueOf(str); Numeric Strings to Basic Types int i = Integer.parseInt(str); long l = Long.parseFloat(str) These methods throw exception (NumberFormatException) if the value of the str does represent an integer. Exception are a OO way of reporting errors. More on it later.

Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used when programs have to handle large amount of data Each value is stored at a specific position Position is called a index or superscript. Base index = 0 The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results.

Arrays - Introduction 69 61 1 index 70 2 89 3 values 23 4 10 5 9 6

Array Syntax Like any other variables, arrays must declared and created before they can be used. The main 3 steps to use the array: Declaring – Allocates an array variable. Creating – Allocates space for the elements and fills the array variable with the address of the first element. Initializing – Filling the elements with initial values.

1- Declaration of Arrays Form 1: Type arrayname[] Form 2: Type [] arrayname; Examples: int[] students; int students[]; Note: we don’t specify the size of arrays in the declaration.

Inspecting a declared array

2- Creation of Arrays After declaring arrays, we need to allocate memory for storage array items. In Java, this is carried out by using “new” operator, as follows: Arrayname = new type[size]; Examples: students = new int[7];

Creating an Array int [] values = new int[6] ; Default values for integer arrays - zero Arrays are Reference Data Types – They contain addresses not values

A program can create several arrays in a single declaration. String [] b = new String[100], x= new String[27];

What happens if … int[] prime=new long[20]; We define int[] prime=new long[20]; MorePrimes.java:5: incompatible types found: long[] required: int[] int[] primes = new long[20]; ^ The right hand side defines an array, and thus the array variable should refer to the same type of array

What happens if … We define MorePrimes.java:5: ']' expected int prime[100]; MorePrimes.java:5: ']' expected long primes[20]; ^ The C++ style is not permitted in JAVA syntax

What happens if … Valid code: Invalid Code: int k=7; long[] primes = new long[k]; Invalid Code: int k; long[] primes =new long[k]; Compilation Output: MorePrimes.java:6: variable k might not have been initialized ^

Accessing Array Elements Index of an array is defined as Positive int, byte or short values Expression that results into these types Any other types used for index will give error long, double, etc. Incase Expression results in long, then type cast to int Indexing starts from 0 and ends at N-1 primes[2]=0; int k = primes[2];

Validating Indexes JAVA checks whether the index values are valid at runtime If index is negative or greater than the size of the array then an IndexOutOfBoundException will be thrown Program will normally be terminated unless handled in the try {} catch {}

What happens if … long[] primes = new long[20]; primes[25]=33; …. Runtime Error: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 25 at MorePrimes.main(MorePrimes.java:6)

Reusing Array Variables Array variable is separate from array itself Like a variable can refer to different values at different points in the program Use array variables to access different arrays int[] primes=new int[10]; …… primes=new int[50]; Previous array will be discarded Cannot alter the type of array

3- Initialisation of Arrays Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified. Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message.

Arrays – Length Arrays are fixed length Length is specified at create time In java, all arrays store the allocated size in a variable named “length”. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 Accessed using the index e.g. int x = students [1]; // x = 40

Arrays – Initializing at Declaration Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80}; Creates and initializes the array of integers of length 5. In this case it is not necessary to use the new operator.

Initializing int [] scores = new int [6] ;

Demonstration long[] primes = new long[20]; primes[0] = 2; long[] primes2=primes; System.out.println(primes2[0]); primes2[0]=5; System.out.println(primes[0]);

Output 2 5

Sample Program class MinAlgorithm { public static void main ( String[] args ) int[] array = { 51, 19, 1, 5, -1, 27, 19, 5 } ; int min=array[0]; // initialize the current minimum for ( int index=0; index < array.length; index++ ) if ( array[ index ] < min ) min = array[ index ] ; System.out.println("The minimum of this array is: " + min ); } }

Question Assume correct declaration of an integer array called numbers. Will the following code compile and work as intended?

Answer Yes

Question Create an array called names that contains 15 Strings. Create should (probably) assume the array is already declared.

Answer(s) names = new String [15] ; or String [] names = new String[15] ;

Question Initialize an array of integers to the values 31, 32, 33, 34, and 35. Use an array initializer.

Answer(s) someName = {31, 32, 33, 34, 35 } ; int [] someName = {31, 32, 33, 34, 35} ;

Write an output statement that outputs the third element in an array Question Write an output statement that outputs the third element in an array

System.out.println(someName[2]); Answer System.out.println(someName[2]); Third element will have an index of 2. Fifth element will have an index of 4. An index of 17 is the 18th element of the array.

Question Write an output statement that will print the number of elements in an array of integers called numbers.

System.out.println(numbers.length); Note - NO parentheses Answer System.out.println(numbers.length); Note - NO parentheses

Write an array declaration of integers using the variable name scores. Question Write an array declaration of integers using the variable name scores.

Key word in the question is “declaration” int [] scores ; Answer Key word in the question is “declaration” int [] scores ; Note – No size is indicated! We are declaring, not creating.

Write an array declaration of Strings using the variable name “teams” Question Write an array declaration of Strings using the variable name “teams”

Answer String [] teams ;

What keyword is used to create an array or any object? Question What keyword is used to create an array or any object?

Answer new

Create an array called val that will contain ten integers. Question Create an array called val that will contain ten integers.

Assuming declaration val = new int[10] ; Not declared Answer(s) Assuming declaration val = new int[10] ; Not declared int [] val = new int [10] ;

Arrays of Arrays Two-Dimensional arrays float[][] temperature=new float[10][365]; 10 arrays each having 365 elements First index: specifies array (row) Second Index: specifies element in that array (column) In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes

2D arrays manipulations Declaration: int myArray [][]; int [][] myArray ; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value; myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}};

Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: int a[][] = new int [3][]; a[0]= new int [3]; a[1]= new int [2]; a[2]= new int [4];

Arrays of Objects Arrays can be used to store objects Circle[] circleArray; circleArray = new Circle[25]; The above statement creates an array that can store references to 25 Circle objects. Circle objects are not created.

Create the Circle objects and stores them in the array. Arrays of Objects Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r);

Array of Arrays Length long[][] primes = new long[20][]; System.out.println(primes.length); //Number of arrays System.out.println(primes[2].length);//Number of elements in the second array OUTPUT: 20 30

Sample Program class unevenExample3 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int row=0; row < uneven.length; row++ ) //changes row System.out.print("Row " + row + ": "); for ( int col=0; col < uneven[row].length; col++ ) //changes column System.out.print( uneven[row][col] + " "); System.out.println(); }

Output Row 0: 1 9 4 Row 1: 0 2 Row 2: 0 1 2 3 4

Class Arrays java.util.Arrays double [] doubleArray= {5,8,15,6,2} Arrays.sort( doubleArray) int x[]= new int[8] Arrays.fill(x)

Class array Helper class java.util.Arrays Search and sort: binarySearch(), sort() Comparison: equals() (many overloaded) Instantiation: fill() (many overloaded) Conversion: asList()