15-Jun-15 Lists in Java Part of the Collections Framework.

Slides:



Advertisements
Similar presentations
Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Advertisements

Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
Professor Evan Korth (adapted from Sun’s collections documentation)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
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.
05 - Containers DRAFT COPY © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
The Java Collections Package C. DeJong Fall 2001.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections –data structures and Algorithms L. Grewe.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
1 TCSS 342, Winter 2005 Lecture Notes Linked List Implementation Weiss Ch. 6, pp Weiss Ch. 17, pp
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Java Programming: From the Ground Up Chapter 17 The Java Collections Framework.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
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.
CS-2852 Data Structures LECTURE 2 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Java Collections CHAPTER 3-February-2003
Java Collections OOP tirgul No
Programming & Data Structures
Data Structures Lakshmish Ramaswamy.
Introduction to Collections
Introduction to Collections
Programming in Java Lecture 11: ArrayList
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Introduction to Collections
Collections Framework
Introduction to Collections
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
ArrayList.
Web Design & Development Lecture 6
Part of the Collections Framework
Java Generics & Iterators
Presentation transcript:

15-Jun-15 Lists in Java Part of the Collections Framework

Kinds of Collections Collection —a group of objects, called elements Set— An unordered collection with no duplicates SortedSet — An ordered collection with no duplicates List— an ordered collection, duplicates are allowed Map— a collection that maps keys to values SortedMap— a collection ordered by the keys Note that there are two distinct hierarchies

Using Collections import java.util.* or import java.util.Collection; There is a sister class, java.util.Collections; that provides a number of algorithms for use with collections: sort, binarySearch, copy, shuffle, reverse, max, min, etc.

Collections Example import java.util.*; // importing Arrays, List, and Collections public class TestCollections { public static void main(String args[]) { String[] array = {"Phil", "Mary", "Betty", "bob"}; List myList = Arrays.asList(array); Collections.sort(myList); System.out.println("Sorted: " + myList); int where = Collections.binarySearch(myList, "bob"); System.out.println("bob is at " + where); Collections.shuffle(myList); System.out.println("Shuffled: " + myList); } Sorted: [Betty, Mary, Phil, bob] bob is at 3 Shuffled: [Betty, bob, Phil, Mary]

Collections are interfaces Collection is actually an interface Each kind of Collection has one or more implementations You can create new kinds of Collections When you implement an interface, you promise to supply the required methods Some Collection methods are optional How can an interface declare an optional method?

Creating a Collection All Collection implementations should have two constructors: A no-argument constructor to create an empty collection A constructor with another Collection as argument All the Sun-supplied implementations obey this rule, but— If you implement your own Collection type, this rule cannot be enforced, because an Interface cannot specify constructors

Collection: Basic operations int size( ); boolean isEmpty( ); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator( );

Collection: Iterator boolean hasNext( ); // true if there is another element Object next( ); // returns the next element (advances the iterator) void remove( ); // Optional // removes the element returned by next } public interface Iterator {

Using an Iterator static void printAll (Collection coll) { Iterator iter = coll.iterator( ); while (iter.hasNext( )) { System.out.println(iter.next( ) ); } } hasNext() just checks if there are any more elements next() returns the next element and advances in the collection Note that this code is polymorphic—it will work for any collection

Set operations A B Set union: A  B A B Set intersection: A  B A B Set difference: A – B

Collection: Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear( ); // Optional addAll, removeAll, retainAll return true if the object receiving the message was modified

Mixing Collection types Note that most methods, such as boolean containsAll(Collection c); are defined for any type of Collection, and take any type of Collection as an argument This makes it very easy to work with different types of Collections

singleton Collections.singleton(e) returns an immutable set containing only the element e c.removeAll(Collections.singleton(e)); will remove all occurrences of e from the Collection c

Collection: Array operations Object[ ] toArray( ); Creates a new array of Object s Object[ ] toArray(SomeType a[ ]); Allows the caller to provide the array Copies the elements to the given array Can throw a ClassCastException if the elements cannot be cast to the correct type for the given array Examples: Object[ ] a = c.toArray( ); String[ ] a; a = (String[ ]) c.toArray(new String[0]);

The List interface The order of elements in a List is important, and there may be duplicate elements Operations are exactly those for Collection int size( ); boolean isEmpty( ); boolean contains(Object e); boolean add(Object e); boolean remove(Object e); Iterator iterator( ); boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear( ); Object[ ] toArray( ); Object[ ] toArray(Object a[ ]);

List implementations List is an interface; you can’t say new List ( ) There are two implementations: LinkedList gives faster insertions and deletions ArrayList gives faster random access It’s poor style to expose the implementation unnecessarily, so: Good: List list = new LinkedList ( ); Not as good: LinkedList list = new LinkedList ( );

Inherited List methods list.remove(e) removes the first e add and addAll add to the end of the list To append one list to another: list1.addAll(list2); To append two lists into a new list: List list3 = new ArrayList(list1); list3.addAll(list2); Again, it's good style to hide the implementation

List: Positional access Object get(int index); // Required -- // the rest are optional Object set(int index, Object element); void add(int index, Object element); Object remove(int index); abstract boolean addAll(int index, Collection c); These operations are more efficient with the ArrayList implementation

List: Searching int indexOf(Object o); int lastIndexOf(Object o); equals and hashCode work even if implementations are different

Interface List: Iteration Iterators specific to Lists: ListIterator listIterator( ); ListIterator listIterator(int index); starts at the position indicated (0 is first element) Methods that ListIterator inherits from Iterator : boolean hasNext( ); Object next( ); void remove( ); Additional methods: boolean hasPrevious() Object previous()

List : Iterating backwards boolean hasPrevious( ); Object previous( ); int nextIndex( ); int previousIndex( ); Think of the iterator as “between” elements Hence, next followed by previous gives you the same element each time

List : More operations void add(Object o); Inserts an object at the cursor position Object set(Object o); // Optional Replace the current element; return the old one Object remove(int index); // Optional Remove and return the element at that position

List: Range-view List subList(int from, int to); allows you to manipulate part of a list Notice the unusual capitalization A sublist may be used just like any other list

The End References: /interfaces/collection.html /interfaces/list.html