Download presentation
Presentation is loading. Please wait.
Published byArleen Harris Modified over 9 years ago
1
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall 645-4739 alphonce@buffalo.edu 1
2
Agenda Announcements – Cell phones / laptops off & away / Name signs out Last time –Finch classroom exercise Today –Collection framework Collection interface ArrayList class HashSet class foreach loop – control structure
3
Collections A collection object can store arbitrarily many references to objects. We will first learn to become users/clients of collections. Next semester we will learn to become builders of collections.
4
java.util.Collection interface All collection classes in Java are subtypes of the java.util.Collection interface. ‘ ’ is new syntax –E is a type variable, and denote the element type of the collection: Collection denotes a collection of String objects Collection denotes a collection of ActionListener objects Among the methods specified in the interface: –boolean add(E item) --- tries to add item to the collection; if this is successful, true is returned, false otherwise –boolean remove(Object item) --- tries to remove item from the collection; if this is successful, true is returned, false otherwise –boolean contains(Object item) --- returns true if item is in the collection, false otherwise –int size() --- return the number of items currently in the collection
5
Two specific collections ArrayList –permits duplicates –allows client to control order of elements HashSet –does not permit duplicates –does not allow client to control order of elements
6
Collections: usage example To declare a variable of type HashSet of String: HashSet names; To create a HashSet of String object, and assign its reference to the variable declared above: names = new HashSet ();
7
Collections: usage example (continued) To add a String to the HashSet: names.add(“Fred”); To remove a String from the HashSet: names.remove(“Fred”);
8
foreach loop A foreach loop is a control structure that repeats a block of code, once for each element in a collection. Syntax for ( : ) ; Example: Collection names = new ArrayList (); names.add(“Fred”); names.add(“Wilma”); for (String s : names) { System.out.println(“Name is “+s); } Prints: Name is Fred Name is Wilma
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.