Java Arrays & Vectors

Similar documents
Java Classes & Primitive Types

Java Classes & Primitive Types

2. The object-oriented paradigm

Array. Prepared By - Rifat Shahriyar

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Computational Expression

Java Simple Data Types

Java. Representing Data. Representing data. Primitive data types

Vector. Lecture 18. Based on Slides of Dr. Norazah Yusof

Array. Array Declaration:

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

CHAPTER 7 OBJECTS AND CLASSES

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

1.00 Lecture 9. Arrays

Introduction to Programming Using Java (98-388)

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Key Java Simple Data Types

Fundamentals of Programming Data Types & Methods

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Java Simple Data Types

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CHAPTER 7 OBJECTS AND CLASSES

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Arrays. Introduction. Figure 3: Examples for Arrays.

Getting started with Java

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Praktische Softwaretechnologie

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

VARIABLES AND TYPES CITS1001

Arrays and Basic Algorithms

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Lecture Set 4: More About Methods and More About Operators

Java Identifiers, Data Types & Variables

Getting started with Java

CSE 431S Type Checking. Washington University Spring 2013

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Computer Science II (20082) Week 1: Review and Inheritance

Exercises Software Development I. 06 Arrays. Declaration, Initialization, Usage // Multi-dimensional Arrays. November 14, 2012

Lab5. Wooseok Kim

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Binghamton University. CS-140 Fall Data Types in Java

Introduction to Programming (Java) 4/12

Decisions in Java IF Statements

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Lecture Set 4: More About Methods and More About Operators

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

array Indexed same type

( &% class MyClass { }

Computer Science is...

(Not Quite) Minijava

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Java Arrays. What could go wrong here? Motivation. Array Definition 9/28/18. Mohammad Ghafari

Inf1-OP. Collections. Perdita Stevens, adapting earlier version by Ewan Klein. January 9, School of Informatics

Object Oriented Programming. Java-Lecture 6 - Arrays

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

Computer Programming: C++

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

1.00/ Lecture 8. Arrays-1

Zheng-Liang Lu Java Programming 45 / 79

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Exam 1 - (20 points)

1B1b Classes in Java Part I

BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 6 Single-dimensional Arrays

CS Programming I: Arrays

type conversion polymorphism (intro only) Class class

CS 101 Spring 2006 Final Exam Name: ID:

Programming Basics. Digital Urban Visualization. People as Flows. ia

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Declarations and Access Control SCJP tips

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

PROGRAMMING FUNDAMENTALS

CS 211: Methods, Memory, Equality

Example: Tax year 2000

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Java Inheritance. Classes implement the concept of ADT:

H212 Introduction to Software Systems Honors

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Review for Test 1 (Chapter 1-5)

Introduction to Computer Science II (ITI 1121) Midterm Examination

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

Building Java Programs

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Programming with Java

Instructor: Eng.Omar Al-Nahal

Programming refresher and intro to C programming

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

Introduction. For instance, if we need to store three whole numbers we can create two integer (int) variables called N1, N2 and tot. tot.

Chapter 2: Basic Elements of Java

Chapter 5 Some useful classes

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 2 EXAMINATIONS 2014/2015 CI101/CI101H. Programming

Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants).

Transcription:

Java Arrays & Vectors Rui Moreira Array is a class (array index starts at 0) n Array of primitive types/values Declaration: //Do not creates array (just the reference/name of array) char[] arraychars; // char arraychars[]; int arrayints[]; // int[] arrayints; Creation: // Allocates memory for holding the primitve values arraychars = new char[127]; // Values are set to \u0000 arraypontos = new Ponto[10]; // Values are set to 0 // We may declare and create at the same time char[] arraychars = new char[127]; int arrayints[] = new int[10]; Initialisation: // Setting array values to a for (int i=0; i<arraychars.length; i++){ arraychars[i]= a ; Rui Moreira 2 Array is a class (has attributelength) n Array of references to objects Declaration: //Do not creates array (just the reference/name of array) Ponto arraypontos[]; // Ponto[] arraypontos; Creation: // Allocates memory for references to objects (not the objects) arraypontos = new Ponto[10]; Values are set to null Initialisation (NB: we may not use/reference the elements of the array if they are not initialised first): // Setting array references to real objects for (int i=0; i<arraypontos.length; i++){ arraypontos[i] = new Ponto(i, i); Rui Moreira 3 1

Declaring, Creating and Initializing Arrays // Create and initializes array of 4 strings String arraystr[] = { John, Mary, Peter, Paul ; // Euivalent to String arraystr[] = new String[4]; arraystr[0]=new String( John ); arraystr[1]=new String( Mary ); arraystr[2]=new String( Peter ); arraystr[3]=new String( Paul ); Rui Moreira 4 Arrays n After creating an array we may not re-dimension it! n We can, however, change the (array) reference variable to a new array: // Declaring, Creating and Initialising an array of 4 Strings String arraystr[] = { John, Mary, Peter, Paul ; // Change the array reference to a new/bigger array arraystr = new String[10]; // We loose the previous values Rui Moreira 5 Exercises n Create Class PrimitiveArrayApp: In the main method declare and create 2 arrays of int, with length 10 and 20; Initialise the array1 with their index values, e.g., array1[i]=i; For each element of the array1 calculate the respective factorial and store it in array2, e.g., array2[i]=factorial.fact(array1[i]); Print out both arrays using different cycles; n Create Class ObjectArrayApp: In the main method declare and create 2 arrays of Ponto and Rectangle, with length 20 and 10; Initialise the array1 with new point objects (each point with coordinates of the array index, e.g., arraypoints[i] = new Ponto(i,i); Initialise the array2 with new rectangle objects (each rectangle uses adjacent points of array1, e.g., arrayrect[i] = new Rectangle(arrayPoints[i], arraypoints[i+1]); Print out both arrays using the tostring() method available in the Ponto and Rectangle classes; Rui Moreira 6 2

Arrays System class n System class provides usefull methods, e.g., arraycopy() int arrayoriginal[] = { 1, 2, 3 ; int arraycopy[] = { 4, 5, 6, 7 ; int size = arrayoriginal.length; // Copy arrayoriginal over arraycopy (overwrite) // Start reading at position 0 of arrayoriginal // Start writing over position 2 of arraycopy // Stop copy when reach end/size arrayoriginal System.arraycopy(arrayOriginal, 0, arraycopy, 2, size); // This will print content of arraycopy // which now is { 4, 1, 2, 3 for (int i=0; i<arraycopy.length; i++){ System.out.print( + arraycopy[i]); Rui Moreira 7 Multidimensional Arrays (Matrix) n Java do not provides multidimensional arrays n but allows the declaration of arrays of arrays of arrays... J // Declaring and creating a rectangular matrix int rectangulararray[][] = new int[4][5]; // Now we can set each element of the matrix ([line][column]) rectangulararray[0][2] = 18; // Sets line 0, column 2 element rectangulararray[1][4] = 6; // Sets line 1, column 4 element rectangulararray[5][5] = 6; // Runtime Exception (OutOfBound) Rui Moreira 8 Multidimensional Arrays (Matrix) n Java allows the declaration of non-rectangular arrays // Declares and creates a (line) array with 4 references // to other arrays of ints (these do not exist yet) int twodimarray[][] = new int[4][]; // Then we may create each (column) array individually // These arrays may have different lengths twodimarray[0] = new int[1]; twodimarray[1] = new int[2]; twodimarray[2] = new int[3]; twodimarray[3] = new int[4]; // NB: this is NOT LEGAL (compile-time error) int twodimarray[][] = new int[][4]; Rui Moreira 9 3

Exercises n Create Matrix Class with static methods for Matrix multiplication mmult() Matrix addition madd() Matrix subtraction msub() Matrix inversion minv()... n Create Scrambler Class It reads a magic-word (characters) from the sdtin; Stores the characters in a array of chars; Then re-orders (scrambles) the characters to a new array; Finally, gives the user n (passed in main args) shots to guess the magic-word. Rui Moreira 10 Vector is a Class n Java provides the java.util.vector class for storing any kind of objects n Vector is like a growable array of Objects, i.e., it can store any kind of objects but not primitive types! // Declaring and creating a variable v // that references a Vector object Vector v = new Vector(), v2 = new Vector(20); // Initial size // We can use the vector to store many objects // Usually in each vector we store only one kind of objects v.addelement(new Ponto(1, 3)); v.addelement(new Ponto(2, 4)); Rui Moreira 11 Vector has following methods (among others) isempty(): returns true if vector is empty (false otherwise) boolean empty = v.isempty(); addelement(object o): adds new element to vector v.addelement(new Ponto(1, 3)); removeelement(int i): removes i-index element from vector v.removeelement(i); removeallelements(): removes all elements from vector v.addelement()); firstelement(): returns first object stored in the vector Ponto p = (Ponto)v.firstElement(); elementat(int i): returns i-index object stored in vector Ponto p = (Ponto)v.elementAt(i); size(): returns number of elements stored in vector int size = v.size(); Rui Moreira 12 4

Exercises n Create PrimitiveVector Class which allow us to store/retrieve primitive types extends Vector implements the following interface: // Add primitive type elements to the vector public void addint(int i): stores Integer public void addfloat(float f): stores Float public void addchar(char c): stores internally Character public void addboolean(boolean b): stores Boolean // Get primitive type elements from the vector public int getintat(int index): returns int element public float getfloatat(int index): returns float element public char getcharat(int index): returns char element public boolean getbooleanat(int index): returns boolean element Rui Moreira 13 5