Introduction to Java 2 Programming Lecture 5 Array and Collections.

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 Java 2 Programming Lecture 3 More Syntax; Working with Objects.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
Introduction to Programming Overview of Week 2 25 January Ping Brennan
Introduction to Programming
For(int i = 1; i
Chapter 8: Arrays.
Introduction to Arrays Chapter What is an array? An array is an ordered collection that stores many elements of the same type within one variable.
Two-Dimensional Arrays Chapter What is a two-dimensional array? A two-dimensional array has “rows” and “columns,” and can be thought of as a series.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Introduction to Computers and Programming Lecture 17: Arrays (cont) Professor: Evan Korth New York University.
CS 112 Intro to Computer Science II Sami Rollins Spring 2007.
1 Lecture Today’s topic Arrays Reading for this Lecture: –Chaper 11.
Introduction to Java Programming Lecture 11 Array II Multidimensional Arrays.
Презентація за розділом “Гумористичні твори”
Центр атестації педагогічних працівників 2014
Галактики і квазари.
Характеристика ІНДІЇ.
Процюк Н.В. вчитель початкових класів Боярської ЗОШ І – ІІІ ст №4
7.1 Arrays Introduction to arrays Any array is a collection of objects or primitives Useful when the number of reference variables is large or.
Java Arrays By Srinivas Reddy.S Arrays Collection of similar data types Stages Declaration Construction Initialization
DREW ALVAREZ AND CORDIE GOODRICH ARRAYS AND ARRAY LISTS.
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.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Java Arrays [Lists] in 10 Minutes. Declaring an array (and its types) int[] myIntArray; double[] myDoubleArray; String[] myStrings; //What’s the pattern?
Week 91 Introduction to Programming Ms. Knudtzon C Period Quarter 2 – Lecture 20 Monday, November 1 st.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 8 Multidimensional Arrays.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
Lecturer : Sakuni Sellapperuma. Introduction An array is a container object that holds a fixed number of values of a single type. The length of an array.
Arrays Array – Group of contiguous memory locations Each memory location has same name Each memory location has same type.
Духовні символи Голосіївського району
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
MCQ Which is the correct syntax for placing the string "boat" into an ArrayList name recVehicles in position 3 (index 2) for the first time? a)recVehicles.set(3,
1 BUILDING JAVA PROGRAMS CHAPTER 7.2 ARRAY TRAVERSAL ALGORITHMS.
Chapter 10 Arrays. Learning Java through Alice © Daly and Wrigley Objectives Declare and use arrays in programs. Access array elements within an array.
Arrays, cont MONDAY – APRIL 6, Review from lab Deep vs Shallow copy array1array array2 = array1; What happens?
 Introducing Arrays  Declaring Array Variables, Creating Arrays, and Initializing Arrays  Copying Arrays  Multidimensional Arrays  Search and Sorting.
1 st Semester Module 7 Arrays อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering Department.
ITEC 320 Lecture 6 More on arrays / Strings. Arrays Review Scope Exceptions Arrays –Dynamic arrays How? Typed and anonymous.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
Introduction to programming in java Lecture 23 Two dimensional (2D) Arrays – Part 3.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Java Programming Language Lecture27- An Introduction.
Announcements & review
Проф. д-р Васил Цанов, Институт за икономически изследвания при БАН
ЗУТ ПРОЕКТ на Закон за изменение и допълнение на ЗУТ
О Б Щ И Н А С И Л И С Т Р А П р о е к т Б ю д ж е т г.
Електронни услуги на НАП
Боряна Георгиева – директор на
РАЙОНЕН СЪД - БУРГАС РАБОТНА СРЕЩА СЪС СЪДЕБНИТЕ ЗАСЕДАТЕЛИ ПРИ РАЙОНЕН СЪД – БУРГАС 21 ОКТОМВРИ 2016 г.
Сътрудничество между полицията и другите специалисти в България
Съобщение Ръководството на НУ “Христо Ботев“ – гр. Елин Пелин
НАЦИОНАЛНА АГЕНЦИЯ ЗА ПРИХОДИТЕ
ДОБРОВОЛЕН РЕЗЕРВ НА ВЪОРЪЖЕНИТЕ СИЛИ НА РЕПУБЛИКА БЪЛГАРИЯ
Съвременни софтуерни решения
ПО ПЧЕЛАРСТВО ЗА ТРИГОДИШНИЯ
от проучване на общественото мнение,
Васил Големански Ноември, 2006
Програма за развитие на селските райони
ОПЕРАТИВНА ПРОГРАМА “АДМИНИСТРАТИВЕН КАПАЦИТЕТ”
БАЛИСТИКА НА ТЯЛО ПРИ СВОБОДНО ПАДАНЕ В ЗЕМНАТА АТМОСФЕРА
МЕДИЦИНСКИ УНИВЕРСИТЕТ – ПЛЕВЕН
Стратегия за развитие на клъстера 2015
Моето наследствено призвание
Правна кантора “Джингов, Гугински, Кючуков & Величков”
Безопасност на движението
Presentation transcript:

Introduction to Java 2 Programming Lecture 5 Array and Collections

Overview Arrays –Working with arrays –Java API support for arrays Collection classes –Types of collection –Working with Collections

Java Arrays – The Basics Declaring an array int[] myArray; int[] myArray = new int[5]; String[] stringArray = new String[10]; String[] strings = new String[] {one, two}; Checking an arrays length int arrayLength = myArray.length; Looping over an array for(int I=0; I<myArray.length; i++) { String s = myArray[i]; }

Java Arrays – Bounds Checking Bounds checking –Java does this automatically. Impossible to go beyond the end of an array (unlike C/C++) –Automatically generates an ArrayIndexOutOfBoundsException

Java Arrays – Copying Dont copy arrays by hand by looping over the array The System class has an arrayCopy method to do this efficiently int array1[] = new int[10]; int array2[] = new int[10]; //assume we add items to array1 //copy array1 into array2 System.arrayCopy(array1, 0, array2, 0, 10); //copy last 5 elements in array1 into first 5 of array2 System.arrayCopy(array1, 5, array2, 0, 5);

Java Arrays – Sorting Again no need to do this by hand. The java.util.Arrays class has methods to sort different kinds of arrays int myArray[] = new int[] {5, 4, 3, 2, 1}; java.util.Arrays.sort(myArray); //myArray now holds 1, 2, 3, 4, 5 Sorting arrays of objects is involves some extra work, as well see later…

Java Arrays Advantages –Very efficient, quick to access and add to –Type-safe, can only add items that match the declared type of the array Disadvantages –Fixed size, some overhead in copying/resizing –Cant tell how many items in the array, just how large it was declared to be –Limited functionality, need more general functionality

Java Collections What are they? –A number of pre-packaged implementations of common container classes, such as LinkedLists, Sets, etc. –Part of the java.util package. Advantages –Very flexible, can hold any kind of object Disadvantages –Not as efficient as arrays (for some uses) –Not type-safe. Store references to Object

Java Collections Two Types of Containers Collections –Group of objects, which may restricted or manipulated in some way –E.g. an ordered to make a List or LinkedList –E.g. a Set, an unordered group which can only contain one of each item Maps –Associative array, Dictionary, Lookup Table, Hash –A group of name-value pairs

Java Collections

Several implementations associated with each of the basic interfaces Each has its own advantages/disadvantages Maps –HashMap, SortedMap Lists –ArrayList, LinkedList Sets –HashSet, SortedSet

Java Collections – The Basics HashMap and ArrayList are most commonly encountered Usual object creation syntax Generally hold references to the interface and not the specific collection –Can then process them generically List myList = new ArrayList(); List otherList = new ArrayList(5); Map database = new HashMap(); Set things = new HashSet();

Java Collections – Adding Items For Collections, use add() List myList = new ArrayList(); myList.add(A String); myList.add(Other String); For Maps, use put() Map myMap = new HashMap(); myMap.put(google, mpMap.put(yahoo,

Java Collections – Copying Very easy, just use addAll() List myList = new ArrayList(); //assume we add items to the list List otherList = new ArrayList(); myList.addAll(myList);

Collections – Getting Individual Items Use get() Note that we have to cast the object to its original type. Collections… String s = (String)myList.get(1); //get first element String s2 = (String)myList.get(10); //get tenth element Maps… String s = (String)myMap.get(google); String s2 = (String)mpMap.get(yahoo);

Collections – Getting all items For Lists, we could use a for loop, and loop through the list to get() each item But this doesnt work for Maps. To allow generic handling of collections, Java defines an object called an Iterator –An object whose function is to walk through a Collection of objects and provide access to each object in sequence

Collections – Getting all items Get an iterator using the iterator() method Iterator objects have three methods: –next() – gets the next item in the collection –hasNext() – tests whether it has reached the end –remove() – removes the item just returned Basic iterators only go forwards –Lists objects have a ListIterator that can go forward and backward

Collections – Getting all items Simple example: List myList = new ArrayList(); //we add items Iterator iterator = myList.iterator(); while (iterator.hasNext()) { String s = (String)iterator.next(); //do something with it }

Collections – Other Functions The java.util.Collections class has many useful methods for working with collections –min, max, sort, reverse, search, shuffle Virtually all require your objects to implement an extra interface, called Comparable

Collections – Comparable The Comparable interface labels objects that can be compared to one another. –Allows sorting algorithms to be written to work on any kind of object –so long as they support this interface Single method to implement public int compareTo(Object o); Returns –A negative number of parameter is less than the object –Zero if theyre equal –A positive number if the parameter is greater than the object

Collections – Comparator Like Comparable, but is a stand-alone object used for comparing other objects –Useful when you want to use your criteria, not that of the implementor of the object. –Or altering the behaviour of a system Many of the methods in the Collections object all a Comparator to be specified Again has single method: public int compare(Object obj1, Object obj2)

Collections – Comparator Example Java String comparison is lexicographic not alphabetic, I.e. based on the character set, not alphabetic order public class AlphaComparison implements Comparator { public int compare(Object obj1, Object obj2) { String s1 = ((String)o1).toLowerCase(); String s2 = ((String)o2).toLowerCase(); return s1.compareTo(s2); }