Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Java POWERED BY: ARVIND DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING RADHA GOVIND GROUP OF INSTITUTIONS,MEERUT.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
15-Jun-15 Lists in Java Part of the Collections Framework.
© 2006 Pearson Addison-Wesley. All rights reserved16-1 Methods in the List Interface (Part 1 of 16)
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 24 : Collections King Fahd University of Petroleum & Minerals College of Computer.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Introduction to Searching and Sorting
12-Jul-15 Lists in Java Part of the Collections Framework.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
1 CSC 222: Computer Programming II Spring 2005 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search  example: spell checker.
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.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
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.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
Collection 105 Yola. To store data in RAM Variables (name all the types with their length) Arrays (one, two or more) Collections and Maps.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
CSC 142 P 1 CSC 142 Collections [Reading: Chapter 10]
Java 2 Collections Bartosz Walter Software Engineering II.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
Jeopardy Print Me Which loop? Call Me Name Me My Mistake Q $100 Q $200 Q $300 Q $400 Q $500 Q $100 Q $200 Q $300 Q $400 Q $500 Final Jeopardy.
List data type(ADT). Lists Elements : a 1,a 2,a 3,… a i-1,a i, a i+1,…a n Null List contains: 0 elements Types of Operations on list 1.Insertion 2.Deletion.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
University of Limerick1 Collections The Collection Framework.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Java Collection Classes Com379PT
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Collections class Method name Description binarySearch(list, value)
Introduction to Searching and Sorting
TCSS 143, Autumn 2004 Lecture Notes
Building Java Programs
Building Java Programs
Collections in Java The objectives of this lecture are:
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Binary search (13.1) binary search: Locates a target value in a sorted array/list by successively eliminating half of the array from consideration. How.
CSE 143 Lecture 2 ArrayIntList, binary search
Part of the Collections Framework
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Presentation transcript:

Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class

Unit 302 Collections Framework’s Classes Object CollectionsAbstractCollection AbstractList AbstractSequentialList LinkedList ArrayList > Collection > List

Unit 303 The ArrayList Class The ArrayList class is List implementation based on a dynamic array. Thus, an ArrayList object is a dynamic array It extends the AbstractList class and implements the List interface of the JCF Before Java 1.2, the functionality of the ArrayList was provided by the Vector class. The Vector class is still part of the JCF. ArrayList is very much like the Vector class except that ArrayList methods are not synchronized Since this class is based on an array, it is better used in applications requiring fast direct access to objects However, the LinkedList class will give better performance for applications requiring frequent insertions and deletions

Unit 304 Example 1: Objects of a Collection This example shows that different objects can be added to the collection. 1 import java.util.ArrayList; 2 import java.util.Collections; 3 class ArrayListOfAllKinds{ 4 public static void main(String args []){ 5 ArrayList theArray = new ArrayList(); 6 theArray.add(new Double(3.7)); 7 theArray.add(new Boolean(true)); 8 theArray.add(new Integer(19)); 9 theArray.add(new String(";-)")); 10 System.out.print(“[“); 11 for(int i=0;i< theArray.size();i++) // loop can be made with iterator 12 System.out.print(theArray.get(i)+” “); 13System.out.println(“]”); 14// printing the whole arrayList object can be done in a single statement because toString() method is defined for the collection object 16 System.out.println(theArray); 17 } 18 }

Unit 305 Example 2: List of Lists This example shows that arrayList objects can be added to other arrayList objects. 1 import java.util.ArrayList; 2 class ListOfLists{ 3 public static void main(String s[]){ 4 ArrayList kfupm=new ArrayList(); 5 ArrayList ics=new ArrayList(); 6 ArrayList coe=new ArrayList(); 7 ArrayList mis=new ArrayList(); 8 String[] icsBasics={"ics102", "ics103", "ics201", "ics202"}; 9 String[] coeBasics={"coe200", "ics102", "ics201", "ics202"}; 10 String[] misBasics={"mis105", "mis345", "mis301", "ics201"}; 11 for (int i=0; i<icsBasics.length; i++) { 12 ics.add(icsBasics[i]); 13 coe.add(coeBasics[i]); 14 mis.add(misBasics[i]); 15 } 16 kfupm.add(ics); 17 kfupm.add(coe); 18 kfupm.add(mis); 19 System.out.println(kfupm); 20 } 21 }

Unit 306 Example 3: Using ArrayList The removeRange() method has protected access modifier in ArrayList. In order to use it, we can extend ArrayList class and override the method and make its access modifier public. 1 import java.util.*; 2 class MyArrayList extends ArrayList{ 3 public MyArrayList(int size){ // if we want to give initial capacity to our arrayList 4 super(size); 5 } 6 public void removeRange (int x, int y){ //protected method of ArrayList 7 super.removeRange(x,y); 8 } 9 } // end of MyArrayList class 10 class TestMyArrayList{ 11 public static void main(String s[]){ 12 MyArrayList c = new MyArrayList(100); //initial capacity. Don’t confusse with size() 13 ListIterator iter = c.listIterator(); 14 for(int i=0; i<6; i++) 15 iter.add(new Integer(i)); // using iterator's add 16 c.add(2,"ICS 201"); // using collection's add 17 System.out.println(c); 18 c.removeRange(3,6); // removes elements from index 3 to 5 19 System.out.println(c); 20 } 21 }

Unit 307 Example 4: Using ArrayList 1 import java.util.*; 2 class TestOtherMethods { 3 public static void main(String s[]){ 4 ArrayList c, c1, c2 = new ArrayList(), c3 = new ArrayList(); 5 ListIterator iter = c3.listIterator(); 6 for(int i=0; i<s.length; i++) 7 iter.add(s[i]); // adding through listIterator 8 for(int i=0; i<10; i++) 9 c2.add(new Integer(i)); // adding through add method of the arrayList object 10 Collections.shuffle(c2); // mix the elements of the arrayList c2 11 System.out.println("Shuffled: "+ c2); 12 c1 = new ArrayList(c3); // making c1 arrayList from the elements of arrayList c3 13 c2.addAll(3,c1); // inserting elements of c1 at index 3 off c2 14 c = (ArrayList)c2.clone(); // making a copy of c2 and storing its address in c 15 c.remove(3); // using remove of collection. Don’t mix with remove of iterator 16 System.out.println(c); 17 System.out.println(c1); 18 System.out.println(c2); 19 System.out.println(c3.containsAll(c1)); // check if all elements of c1 are present in c3 20 } 21 }

Unit 308 Example 5: Splitting arrayList alternatively import java.util.*; class SplitList { public static void main(String[] args) { ArrayList a=new ArrayList(); ArrayList b=new ArrayList();ArrayList c=new ArrayList(); Random rd=new Random(); for (int i=0;i<20;i++) a.add(new Integer(rd.nextInt(101)-50)); // generates random number between -50 and 50 Iterator ia = a.iterator(); // iterator for a //put elements of a alternatively in b and c while (ia.hasNext()) { b.add(ia.next()); if (ia.hasNext()) c.add(ia.next()); } System.out.println(a); System.out.println(b); System.out.println(c); }}

Unit 309 Example 6: removing similar objects import java.util.*; class RemoveSimilar { public static void main(String[] args) { String[] words={"apple","cat","pen","tea","tree","like","like","ics201"}; ArrayList myWords = new ArrayList(Arrays.asList(words)); ArrayList myWords2=(ArrayList)myWords.clone(); int n = myWords.size(); // for (int i = 0; i < n; i++) { // wrong way of making loop indexoutofBound exception for (int i=0;i<myWords.size();i++){ // still wrong, second like is skipped if ("like".equals(myWords.get(i))) myWords.remove(i); } System.out.println("One like word left --> "+myWords); // right way of making loop to remove all "like" words for(int i=0; i<myWords2.size();) { // the increment part empty if ("like".equals(myWords2.get(i))){ myWords2.remove(i);} else i++; } System.out.println("All like words removed --> "+myWords2); }}

Unit 3010 The Collections Class The Collections class is a utility class. It contains static methods for manipulating collection objects. Some of the methods were already used in previous examples. The Arrays class is also a utility class. It contains static methods for manipulating arrays. One useful method used is asList() to convert an array into a list. The following are the most frequently used methods of the Collections class. –static int binarySearch(List list, Object o) // list sorted according to natural ordering –static int binarySearch(List list, Object o, Comparator c)// list sorted according to comparator –static void sort(List list) // sorts according to natural ordering –static void sort(List list, Comparator c) // sorts according to comparator –static void copy (List dest, List src) // copies all elements from src list to dest list –static Object max(Collection c) // returns max according to natuaral ordering –static Object min(Collection c) // returns min according to natuaral ordering –static void reverse(List list) //Reverses the order of the elements in the specified list –static void shuffle(List list) // Randomly permutes the specified list The next example uses sort and binary search methods

Unit 3011 Example 7: Sorting arrayLists import java.util.*; import javax.swing.*; class SortingList { public static void main(String[] args) { ArrayList list = new ArrayList(); // Get the students' names String s; do{ s=JOptionPane.showInputDialog(null,"Student Name"); if (s!=null) list.add(s); }while(s!=null); // Sort the list in alphabetical order Collections.sort(l); // sorting based on compareTo method implemented by String class Iterator i = list.iterator(); while(i.hasNext()) System.out.println(i.next()); // Print the list using the iterator Collections.sort(l,new Comparator(){ // sort the list according to the comparator object public int compare(Object b1, Object b2) { return ((String)b1).length()-((String)b2).length(); }}); System.out.println("list sorted by length of name "+l); // print using toString() of arrayList }}

Unit 3012 Example 8: Searching Collections import java.util.*; class BankAccount implements Comparable{ private int accountNumber; private String name; private double balance; public BankAccount(int accountNumber, String name, double balance){ this.accountNumber = accountNumber; this.name = name; this.balance = balance; } public BankAccount(int accountNumber, String name){ this(accountNumber, name,0); } public String getName() { return name; } public int compareTo(Object object){ BankAccount account = (BankAccount) object; return accountNumber - account.accountNumber; } public String toString(){ return accountNumber + " " + name + " " + balance + " SR"; }

Unit 3013 Example 8: Searching Collections (cont’d) class SortingAndSearching{ public static void main(String[] args){ ArrayList list = new ArrayList(); list.add(new BankAccount(9234, "Ahmad", )); list.add(new BankAccount(8000, "Abubakar", )); list.add(new BankAccount(6000, "Yusuf", 6000 )); list.add(new BankAccount(9975, "Zubeir", )); System.out.println("Sorted in increasing order of Account Number:"); Collections.sort(list); System.out.println(list); System.out.println("Sorted in decreasing order of Customer name:"); Collections.sort(list, new Comparator(){ public int compare(Object object1, Object object2){ BankAccount account1 = (BankAccount) object1; BankAccount account2 = (BankAccount)object2; String string1 = account1.getName(); String string2 = account2.getName(); return string2.compareTo(string1); }}); System.out.println(list); Collections.sort(list); System.out.println("Sorted again in increasing order of Account Number: \n"+list); BankAccount ba1 = new BankAccount(6000, "Yusuf"); BankAccount ba2 = new BankAccount(1000, "Yassin"); System.out.println(Collections.binarySearch(list, ba1)); //present at index 0 System.out.println(Collections.binarySearch(list, ba2)); // not present (-1) printed }}