Recitation 5 Enums and The Java Collections classes/interfaces 1.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

New features in JDK 1.5 Can these new and complex features simplify Java development?
This recitation 1 An interesting point about A2: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Java Review Interface, Casting, Generics, Iterator.
AbstractClassesInterfacesPolymorphism1 Abstract Classes, Interfaces, Polymorphism Barb Ericson Georgia Tech April 2010.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Chapter 19 Java Data Structures
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Java's Collection Framework
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.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
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.
Recitation 1 CS0445 Data Structures Mehmud Abliz.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Java Programming: Program Design Including Data Structures 1 Vectors The class Vector can be used to implement a list Unlike an array, the size of a Vector.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
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.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Generics with ArrayList and HashSet 1 ge·ner·ic adjective \jə ̇ˈ nerik, -rēk\ relating or applied to or descriptive of all members of a genus, species,
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Comparing ArrayLists and Arrays. ArrayLists ArrayLists are one type of flexible-size collection classes supported by Java –ArrayLists increase and decrease.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
1 Enums (Chapter 4) To enumerate is: to name things one after another in a list Java has a type, called an enum, where a programmer specifies a finite.
Object Oriented Programming in Java Habib Rostami Lecture 7.
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.
Introduction to Enumerations CMSC 202. Enumerated Values Enumerated values are used to represent a set of named values. Historically in Java (and other.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
Building Java Programs
JAVA COLLECTIONS LIBRARY
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Enums and The Java Collections classes
Implementing ArrayList Part 1
Road Map CS Concepts Data Structures Java Language Java Collections
Building Java Programs
Collections in Java The objectives of this lecture are:
Collections Framework
Hashing in java.util
Lecture 7: Linked List Basics reading: 16.2
Web Design & Development Lecture 6
Presentation transcript:

Recitation 5 Enums and The Java Collections classes/interfaces 1

How do we represent... Enums ●Suits - Clubs, Spades, Diamonds, Hearts ●Directions - North, South, East, West ●Days of week - Monday, Tuesday... ●Planets - Mercury, Venus, Earth... Other small sets of values that do not change 2

Using constants Enums public class Suit { public static final int CLUBS = 0; public static final int SPADES = 1; public static final int DIAMONDS = 2; public static final int HEARTS = 3; } Problems: ●no type checking ●readability int getSuit() {...} void setSuit(int suit) {...} 3

Objects as constants Enums public class Suit { public static final Suit CLUBS = new Suit(); public static final Suit SPADES = new Suit(); public static final Suit DIAMONDS = new Suit(); public static final Suit HEARTS = new Suit(); private Suit() {} } no new Suits can be created cannot modify Suit objects Suit v; … if (v == Suit.CLUBS) { …} use == 4

Enum declaration Enums public enum Suit {CLUBS, SPADES, DIAMONDS, HEARTS}; static final variables of enum Suit could be any access modifier name of enum new keyword 5

About enums Enums 1.Can contain methods, fields, constructors a.Suit.HEARTS.getColor(); 1.Suit’s constructor is private! a.Cannot instantiate except for initial constants 1.Suit.values() returns a Suit[] of constants in enum 6

Demo: Enums in action Create a class PlayingCard and class Deck. What would be the fields for a PlayingCard object? Enums 7

Enum odds and ends Enums 1.Suit is a subclass of java.lang.Enum 2. ordinal() returns position in list (i.e. the order it was declared) a. Suit.CLUBS.ordinal() == 0 3.enums automatically implement Comparable a. Suit.CLUBS.compareTo(Suit.HEARTS) uses the ordinals for Clubs and Hearts 4. toString() of Suit.CLUBS is “CLUBS” a.you can override this! 8

Enum odds and ends Enums 5. switch statement Suit s = Suit.CLUBS; switch(s) { case CLUBS: case SPADES: color= “black”; break; case DIAMONDS: case HEARTS: color= “red”; break; } s == Suit.CLUBS is true switch statements are fall through! break keyword is necessary. 9

Collections and Map The Collections classes and interfaces are designed to provide implementations of bags (like a bag of objects with duplicates allowed) sets lists Stacks queues 10 You will see in later assignments how easy it is to use these

Power of inheritance and interfaces Collections and Map Format of ArrayList object Object AbstractCollection AbstractList ArrayList Collection Iterable List 11

Important interfaces Collections and Map Collection add(E); contains(Object); isEmpty(); remove(Object); size();... List get(int); indexOf(int); add(int,E);... Set No new methods in Set, just changes specifications Map put(K,V); get(Object); 12

Important classes Collections and Map Collection List Set LinkedList HashSet ArrayList HashMap Map 13

Queues? Stacks? Collections and Map Collection Queue LinkedList Deque “Double Ended Queue” ArrayDeque 14

Iterating over a HashSet or ArrayList 15 HashSet Object Fields contain a set of objects HashSet() add(Object) contains(Object) size() remove(Object) … s HashSet HashSet s= new HashSet(); … store values in the set … for (Object e : s) { System.out.println(c); } Body of loop is executed once with e being each element of the set. Don’t know order in which set elements are processed

Collections problems Collections and Map 1.Remove duplicates from an array 2.Find all negative numbers in array 3.Create ransom note 4.Implement a Stack with a max API 5.Braces parsing 16

Collections problems Collections and Map Complete Integer[] removeDuplicates(int[]) Remove all duplicates from an array of integers. Very useful HashSet method: hs.toArray(new Integer[hs.size()]); 17

Collections problems Collections and Map Find Negative Numbers Find all negative numbers in array and return an array with those integers Very useful ArrayList method: lst.toArray(new Integer[lst.size()]); 18

Collections problems Collections and Map Create Ransom Note Given a note (String) that you would like to create and a magazine (String), return whether you can create your note from the magazine letters. 19

Collections problems Collections and Map Implement a Stack with a max() function in O(1) time No matter how full the stack is, the max function should be in constant time. (ie you should not iterate through the Linked List to find the maximum element) 20

Collections problems Collections and Map Braces parsing in O(n) time Return whether a String has the right format of square brackets and parenthesis. e.g. “array[4] = ((( new Integer(3) )));” <- is true “( ) [ ] ]” <- is false “)(” <- is false “ ( [ ) ] ” <- is false 21

Collections problems Collections and Map Print a binary tree in level-order Output: Challenge Problem Output: