Problem Solving # 9: ArrayList, Collections and More ICS201-071.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) Generics.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Collections –data structures and Algorithms L. Grewe.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
CompSci Arrays  Aggregate data type  Deal with items of same type  Lists of words  Numbers  Analogies  Mailboxes in post office  CD racks.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.
Lists What to do?. Lists  A list is a linear arrangement of data elements.  Items are arranged in sequential (linear) order  Items are therefore ordered.
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.
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
What is Iterator Category: Behavioral Generic Way to Traverse Collection Not Related to Collection Implementation Details Not Related to the direction/fashion.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49,
Comparing ArrayLists and Arrays. ArrayLists ArrayLists are one type of flexible-size collection classes supported by Java –ArrayLists increase and decrease.
COMP More About Arrays Yi Hong June 05, 2015.
IMPLEMENTATION OF CLASS EXTENT by Paweł Świetlicki.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Exposure Java 2011 APCS Edition
Sixth Lecture ArrayList Abstract Class and Interface
COP 3503 FALL 2012 Shayan Javed Lecture 8
Generics.
An Introduction to Java – Part I, language basics
Collections James Brucker.
Code Refresher Test #1 Topics:
slides created by Alyssa Harding
Objects with ArrayLists as Attributes
Presentation transcript:

Problem Solving # 9: ArrayList, Collections and More ICS

2 Outline Review of Key Topics Review of Key Topics Problem 1: Using ArrayList Class … Problem 1: Using ArrayList Class … Problem 2: Iterators and ListIterators Problem 2: Iterators and ListIterators Problem 3: Applications of ArrayList …. Problem 3: Applications of ArrayList …. Problem 4: Java Collections … Problem 4: Java Collections … Problem 5: Java Generics … Problem 5: Java Generics …

3 ArrayList Class: Tips import java.util.ArrayList; public class MyArrayList1 { public static void main(String[] args) { Seller sel = new Seller(); Buyer buy = new Buyer(); // declare an array list of type Seller ArrayList list = new ArrayList (); list.add(sel); // add object of type Seller which is permisible list.add(buy); // this statement will give an error } } // Classes Seller and Buyer are supposed defined earlier….

4 ArrayList Class: Tips (Cont’d) import java.util.ArrayList; public class MyArrayList2 { public static void main(String[] args) { // declare an array list of Integer ArrayList list = new ArrayList (); list.add(5); // Automatic boxing list.add(new Integer(6)); list.add(new Integer(6)); int value = list.get(1); int value = list.get(1); System.out.println(value); } } System.out.println(value); } }

5 ArrayList Class: Tips (Cont’d) import java.util.*; public class ArrayListGenericDemo { public static void main(String[] args) { ArrayList data = new ArrayList (); data.add("hello"); data.add("goodbye"); // data.add(new Date()); This won't compile! Iterator it = data.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } } }

6 Java Generics: Tips class GenCons { private double val; GenCons(T arg) { val = arg.doubleValue(); } void showval() { System.out.println("val: " + val); } } public class GenConsDemo { public static void main(String args[]) { GenCons test = new GenCons(100); GenCons test2 = new GenCons(123.5F); test.showval(); test2.showval(); } }

7 Java Generics: Tips (Con’d) public class GenMethDemo { // Determine if an object is in an array. static boolean isIn(T x, V[] y) { for(int i=0; i boolean isIn(T x, V[] y) { for(int i=0; i < y.length; i++) if(x.equals(y[i])) return true; return false; } public static void main(String args[]) { // Use isIn() on Integers. Integer nums[] = { 1, 2, 3, 4, 5 }; if(isIn(2, nums)) System.out.println("2 is in nums"); if(!isIn(7, nums)) System.out.println("7 is not in nums"); System.out.println(); // Use isIn() on Strings. String strs[] = { "one", "two", "three", "four", "five" }; if(isIn("two", strs)) System.out.println("two is in strs"); if(!isIn("seven", strs)) System.out.println("seven is not in strs"); // Opps! Won't compile! Types must be compatible. // if(isIn("two", nums)) // System.out.println("two is in strs"); } }

8 HashSet: Tips import java.util.*; public class HashSet1 { public static void main( String[] args ) { public static void main( String[] args ) { HashSet set = new HashSet (); HashSet set = new HashSet (); set.add( new Integer( 6 ) ); set.add( new Integer( 6 ) ); set.add( new Integer( 1 ) ); set.add( new Integer( 1 ) ); set.add( new Integer( 4 ) ); set.add( new Integer( 4 ) ); System.out.println( set ); System.out.println( set ); System.out.println(); System.out.println(); System.out.println( "Show that duplicates cannot be added." ); System.out.println( "Show that duplicates cannot be added." ); set.add( new Integer( 8 ) ); set.add( new Integer( 8 ) ); System.out.println( "New contents are " + set ); System.out.println( "New contents are " + set ); boolean value = set.add( new Integer( 4 ) ); boolean value = set.add( new Integer( 4 ) ); if(value) if(value) System.out.println(" A duplicate value has been added!"); System.out.println(" A duplicate value has been added!"); else else System.out.println(" A duplicate value can NOT be added!"); System.out.println(" A duplicate value can NOT be added!"); System.out.println( "New contents are " + set ); System.out.println( "New contents are " + set ); } }

Form Groups of 3 Students and Work on the Following Problem

10 Problem 1: Using ArrayList Class to store Student data. Student data: id, name, gpa and major

11 Problem 1 … a) Define the Student class b) Write the test class c) Search for a specific Student record

12 Solution

13 Problem 2 … a) Search for a specific Student record using an iterator b) Remove all the duplicate copies of a specific Student record using an iterator

14 Solution

15 Problem 3 Swapping a list of ArrayList elements: a) Using the for-each loop c) Using iterators (….)

16 Solution

17 Problem 4 Consider the following code…

18 Problem 4 import java.util.*; public class CollectionTest { public static void main(String [] args) { System.out.println( "Collection Example!\n" ); int size; // Create a collection HashSet collection = new HashSet (); String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator; //Adding data in the collection collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4); System.out.print("Collection data: "); //Create a iterator iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); // Get size of a collection size = collection.size(); if (collection.isEmpty()){ System.out.println("Collection is empty"); } else{ System.out.println( "Collection size: " + size); } System.out.println(); import java.util.*; public class CollectionTest { public static void main(String [] args) { System.out.println( "Collection Example!\n" ); int size; // Create a collection HashSet collection = new HashSet (); String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator; //Adding data in the collection collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4); System.out.print("Collection data: "); //Create a iterator iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); // Get size of a collection size = collection.size(); if (collection.isEmpty()){ System.out.println("Collection is empty"); } else{ System.out.println( "Collection size: " + size); } System.out.println(); // Remove specific data collection.remove(str2); System.out.println("After removing [" + str2 + "]\n"); System.out.print("Now collection data: "); iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); size = collection.size(); System.out.println("Collection size: " + size + "\n"); //Collection empty collection.clear(); size = collection.size(); if (collection.isEmpty()){ System.out.println("Collection is empty"); } else{ System.out.println( "Collection size: " + size); } } }

19 Problem 5 Define a generic class as follows: Define a generic class as follows: class Gen { T ob; // declare an object of type T Gen(T o) { ob = o; } T getob() { return ob; } void showType() { System.out.println("Type of T is " + ob.getClass().getName()); } }

20 Problem 5 (Cont’d) public class GenDemo { public static void main(String args[]) { Gen iOb; iOb = new Gen (88); iOb.showType(); int v = iOb.getob(); System.out.println("value: " + v); System.out.println(); Gen strOb = new Gen ("Generics Test"); strOb.showType(); String str = strOb.getob(); System.out.println("value: " + str); } }