Arrays, ArrayLists, and Collections. Rationale Suppose we have a program to compute the average of three numbers. We could write a simple little method.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
© 2006 Pearson Addison-Wesley. All rights reserved16-1 Methods in the List Interface (Part 1 of 16)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Chapter 19 Java Data Structures
Java Collections. Collections, Iterators, Algorithms CollectionsIteratorsAlgorithms.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
The Java Collections Framework (JCF) Introduction and review 1.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Object Oriented Programming Ders 10: Data Structures Mustafa Emre İlal
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
Chapter 18 Java Collections Framework
Computer Science 209 Software Development Java Collections.
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Data structures Abstract data types Java classes for Data structures and ADTs.
Collections –data structures and Algorithms L. Grewe.
Data structures and algorithms in the collection framework 1.
Collection 105 Yola. To store data in RAM Variables (name all the types with their length) Arrays (one, two or more) Collections and Maps.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
1 Interfaces in Java’s Collection Framework Rick Mercer.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Java Data Structures
Software Development Java Collections
University of Central Florida COP 3330 Object Oriented Programming
CSE 143 Lecture 9 References and Linked Nodes reading: 3.3; 16.1
Java Collections Framework
Arrays Week 2.
Collections Framework
CS 240 – Advanced Programming Concepts
Presentation transcript:

Arrays, ArrayLists, and Collections

Rationale Suppose we have a program to compute the average of three numbers. We could write a simple little method to compute the average given the three numbers passed in.

/** * Suppose we want to compute the average of a set of numbers. We might be able to justify not * using arrays when we only need to compute the average for a couple of values, but when the * number of values we need to compute the average for gets larger the harder it is to compute * work with individual variables for each....hence the need for arrays. **/ public class RationaleForArrays { /** * Where we could do this for simple cases like computing the average for three numbers. **/ public double computeAverage(double n0, double n1, double n2) { return (n0 + n1 + n2)/3.0; } public static void main(String argv[]) { RationaleForArrays rationale = new RationaleForArrays(); /* * Although we could justify explicitly individual values when we are * dealing with a small number of variables... */ double number0 = 0.00 * 1.001; double number1 = 1.00 * 1.001; double number2 = 2.00 * 1.001; System.out.printf("Average for %3d numbers : %8.4f -- without array\n", 3, rationale.computeAverage(number0, number1, number2)); } OUTPUT: Average for 3 numbers : without array

What if it was more than 3 numbers … What if it was 100 numbers … or a 1,000 or 10,000 or even a million.. What if you did not know the number of numbers you need to compute the average of when you were writing your routine? We need the ability to get/set a list of these numbers … sounding like arrays

Java Arrays Arrays are a structured way to store multiple homogenous data in a single variable Index through the array starting with 0 to length-1 If you try to access outside the array’s valid range you get an ArrayIndexOutOfBoundsException Must be declared up front with some predetermined size and type Can be single or multidimensional –single dimensional are a series of values (think of a column of values) –multiple dimensional are implemented as an array of arrays (think of rows of columns) Can store primitives or object type data

Working with Arrays Declaring // single dimensional double score[];// same as double[] score; Declaring and Creating an Array doublescore[] = new double[100]; doublematrix[][] = new double[10][10]; Declaring and Initializing an Array double score[] = { 98.0, 87.5, }; double matrix[][] = { { 10.0, 20.0 }, { 30.0, 40.0 }, };

Some Examples of Arrays public void examplesOfArrays() { double score[] = { 98.0, 87.5, }; double matrix[][] = { { 10.0, 20.0 }, { 30.0, 40.0 }, }; System.out.println("\nSingle dimenstional array of scores:"); for(int i = 0; i < score.length; ++i) System.out.printf("Score %2d = %4.2f\n", i, score[i]); System.out.println("\n\nMatrix:"); for(int row = 0; row < matrix.length; ++row) { for(int col = 0; col < matrix[0].length; ++col) { System.out.printf(" %4.2f", matrix[row][col]); } System.out.println(); } OUTPUT: Single dimensional array of scores: Score 0 = Score 1 = Score 2 = Matrix:

So lets go back and look at that computing the average now with arrays …

/** * Suppose we want to compute the average of a set of numbers. We might be able to justify not * using arrays when we only need to compute the average for a couple of values, but when the * number of values we need to compute the average for gets larger the harder it is to compute * work with individual variables for each....hence the need for arrays. **/ public class RationaleForArrays { /** * As the number of values increase or non-deterministic at compile time. **/ public double computeAverage(double number[]) { double sum = 0.0; for(int i = 0; i < number.length; ++i) sum += number[i]; return sum/number.length; } public static void main(String argv[]) { RationaleForArrays rationale = new RationaleForArrays(); double number[] = null; number = new double[3]; for(int i = 0; i < 3; ++i) number[i] = i * 1.001; System.out.printf("Average for %3d numbers : %8.4f -- with array\n", number.length, rationale.computeAverage(number)); number = new double[100]; for(int i = 0; i < 100; ++i) number[i] = i * 1.001; System.out.printf("Average for %3d numbers : %8.4f -- with array\n", number.length, rationale.computeAverage(number)); /* * Did you notice that the code did not change when we changed * from 3 numbers to :-) */ } OUTPUT: Average for 3 numbers : with array Average for 100 numbers : with array

What else should we know about arrays? public void moreExamplesOfArrays() { String sa1[] = { "zero", "one", "two", "three", "four", "five" }; String sa2[] = { "0", "1", "2", "3", "4", "5" }; String sa3[] = { "d", "b", "f", "a", “c" }; /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sa1.length; ++i) System.out.printf("\t%s", sa1[i]); System.out.println(); /* copying array elements * System.arraycopy(src, srcPos, dest, destPos, length) */ System.arraycopy(sa2, 0, sa1, 0, 2); System.out.printf("After the copy \n"); for(int i = 0; i < sa1.length; ++i) System.out.printf("\t%s", sa1[i]); System.out.println(); /* sorting array elements */ System.out.printf("Before the sort \n"); for(int i = 0; i < sa3.length; ++i) System.out.printf("\t%s", sa3[i]); System.out.println(); Arrays.sort(sa3); System.out.printf("After the sort \n"); for(int i = 0; i < sa3.length; ++i) System.out.printf("\t%s", sa3[i]); System.out.println(); } OUTPUT: from arraycopy(…) Original Strings zero one two three four five After the copy 0 1 two three four five This is the same as setting the values individually in the code. Hence, we get no performance enhancement for doing this, just convince. OUTPUT: from Arrays.sort(…) Before the sort d b f a c After the sort a b c d f

Given what we know now … Can you think of how we could implement dynamic arrays?

Instead of us having to doing worrying about dynamically resizing, we can use an ArrayList

ArrayList Comparing ArrayList to Java arrays: –similar: a sequence of objects each object is index from 0 to size -1 –different: only can contain objects (no primitives) size() instead of length array[i] = value  array.set(i, value) can grow and shrink in size

Important ArrayList Methods Constructors –ArrayList(Collection) –ArrayList(initialSize) Methods –add(index, object)add an element to the list at a given location –add(object)add a given element to the list –addAll(Collection)add all the elements to the list –clear()remove all the elements –get(index)get the object at a specified index –remove(index)remove the element at a specified index –set(index, object)set a given object at a given index –size()number of elements in the list –toArray()convert to an array –trimToSize()trim to the current size

ArrayList Examples public void examplesOfArrayList() { ArrayList sal1 = new ArrayList (3); sal1.add("d"); sal1.add("b"); sal1.add("a"); /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); } OUTPUT: Original Strings d b a

ArrayList is a Collection As a result the Collections utility class can be used to help out. –binary search for an element –copy a list to another list –enumerate over a collection –fill a list with a given object –reverse –rotate –shuffle –sort –swap to elements in a list

Collections Examples public void examplesOfArrayList() { ArrayList sal1 = new ArrayList (3); sal1.add("d"); sal1.add("b"); sal1.add("a"); /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.sort(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the sort\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.reverse(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the reverse\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); } OUTPUT: Original Strings d b a After the sort a b d After the reverse d b a

public void examplesOfArrayList() { ArrayList sal1 = new ArrayList (3); sal1.add("d"); sal1.add("b"); sal1.add("a"); /* indexing array elements */ System.out.printf("\n\nOriginal Strings\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.sort(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the sort\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.reverse(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the reverse\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.rotate(sal1, 1); /* use of Collections utility */ System.out.printf("\n\nAfter the rotate\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.shuffle(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the shuffle\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); Collections.shuffle(sal1); /* use of Collections utility */ System.out.printf("\n\nAfter the shuffle\n"); for(int i = 0; i < sal1.size(); ++i) System.out.printf("\t%s", sal1.get(i)); System.out.println(); } OUTPUT: Original Strings d b a After the sort a b d After the reverse d b a After the rotate a d b After the shuffle b d a After the shuffle a d b

The Collections Framework Collection Interfaces –Set A collection of not duplicating elements Only contains methods exposed in Collection but adds uniqueness to the elements. Implementations: HashSet, TreeSet, LinkedHashSet –List A collection of elements (can contain duplicates) Additions to Collection: positional access, search, iteration, range view Implementations: Vector (retrofitted), ArrayList, LinkedList –Queue A collection of elements that follow a FIFO pattern Implementations: LinkedList, PriorityQueue –Map A collection of name-value pairs. Names can not be duplicated. Implementations: HashMap, TreeMap, LinkedHashMap Object Ordering –SortedSet – Iterator & toArray return the elements in “sorted” order –SortedMap - Iterator & toArray return keys, values, or entries in “sorted” order

The Collections Framework Hash Table Resizable Array Balanced Tree Linked List Hash Table + Linked List SetHashSetTreeSetLinkedHashSet ListArrayListLinkedList MapHashMapTreeMapLinkedHashMap