엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

Size: px
Start display at page:

Download "엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University"

Transcription

1 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University C O P Y R I G H T S E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D

2 - String - Overloading - Operations - Formatter Class - Scanner - Array Outline - Containers - About Containers - Container Disadvantage - Printing Containers - Container Taxonomy C O P Y R I G H T S E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D

3 Immutable Strings Objects of the String class are immutable. String class every method in the class that appears to modify a String actually creates and returns a brand new String object containing the modification. The original String is left untouched. import static net.mindview.util.print.*; public class Immutable { public static String upcase(string s) { return s.touppercase(); public static void main(string[] args) { String q = "howdy"; print(q); // howdy String qq = upcase(q); print(qq); // HOWDY print(q); // howdy >> howdy HOWDY howdy

4 Overloading + vs. StringBuilder operator + has been overloaded for String objects. Overloading an operation has been given an extra meaning when used with a particular class. (The + and += for String are the only operators that are overloaded in Java, and Java does not allow the programmer to overload any others.) The + operator allows you to concatenate Strings public class Concatenation { public static void main(string[] args) { String mango = "mango"; String s = "abc" + mango + "def" + 47; System.out.println(s); >> abcmangodef47

5 Overloading + vs. StringBuilder Cont d public class UsingStringBuilder { public static Random rand = new Random(47); public String tostring() { StringBuilder result = new StringBuilder("["); for(int i = 0; i < 25; i++) { result.append(rand.nextint(100)); result.append(", "); result.delete(result.length()-2, result.length()); result.append("]"); return result.tostring(); public static void main(string[] args) { UsingStringBuilder usb = new UsingStringBuilder(); System.out.println(usb); >> [58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9, 78, 98, 61, 20, 58, 16, 40, 11, 22, 4]

6 Overloading + vs. StringBuilder append(a + ": " + c) the compiler will jump in and start making more StringBuilder objects again. StringBuilder has a full complement of methods insert( ), replace( ), substring( ) and even reverse( ) But the ones you will generally use are append( ) and tostring( ). Note the use of delete( ) to remove the last comma and space before adding the closing square bracket. StringBuilder introduced in Java SE5 Prior : StringBuffer, which ensured thread safety

7 Operations on Strings

8 Operations on Strings Cont d

9

10 System.out.format() public class SimpleFormat { public static void main(string[] args) { int x = 5; double y = ; // The old way: System.out.println("Row 1: [" + x + " " + y + "]"); // The new way: System.out.format("Row 1: [%d %f]\n", x, y); // or System.out.printf("Row 1: [%d %f]\n", x, y); >> Row 1: [ ] Row 1: [ ] Row 1: [ ]

11 The Formatter class %[argument_index$][flags][width][.precision]conversion Need to control the minimum size of a field. This can be accomplished by specifying a width. The Formatter guarantees that a field is at least a certain number of characters wide by padding it with spaces By default the data is right justified this can be overridden by including a - in the flags section.

12 The Formatter class Cont d import java.util.*; public class Receipt { private double total = 0; private Formatter f = new Formatter(System.out); public void printtitle() { f.format("%-15s %5s %10s\n", "Item", "Qty", "Price"); f.format("%-15s %5s %10s\n", "----", "---", "-----"); public void print(string name, int qty, double price) { f.format("%-15.15s %5d %10.2f\n", name, qty, price); total += price; public void printtotal() { f.format("%-15s %5s %10.2f\n", "Tax", "", total*0.06); f.format("%-15s %5s %10s\n", "", "", "-----"); f.format("%-15s %5s %10.2f\n", "Total", "", total * 1.06); public static void main(string[] args) { Receipt receipt = new Receipt(); receipt.printtitle(); receipt.print("jack s Magic Beans", 4, 4.25); receipt.print("princess Peas", 3, 5.1); receipt.print("three Bears Porridge", 1, 14.29); receipt.printtotal(); >> Item Qty Price Jack s Magic Be Princess Peas Three Bears Por Tax Total 25.06

13 Formatter conversions

14 String.format( ) String.format() a static method which takes all the same arguments as Formatter s format( ) but returns a String. It can come in handy when you only need to call format( ) once: public class DatabaseException extends Exception { public DatabaseException(int transactionid, int queryid, String message) { super(string.format("(t%d, q%d) %s", transactionid, queryid, message)); public static void main(string[] args) { try { throw new DatabaseException(3, 7, "Write failed"); catch(exception e) { System.out.println(e); >> DatabaseException: (t3, q7) Write failed

15 Creating regular expressions

16 Creating regular expressions Cont d

17 Creating regular expressions

18 Scanner The Scanner class added in Java SE5 relieves much of the burden of scanning input The Scanner constructor It can take just about any kind of input object, including a File object (which will also be covered in the I/O chapter), an InputStream, a String, or in this case a Readable With Scanner, the input, tokenizing, and parsing are all ensconced in various different kinds of "next" methods. A plain next( ) returns the next String token there are "next" methods for all the primitive types (except char) as well as for BigDecimal and Biglnteger. All of the "next" methods block they will return only after a complete data token is available for input.

19 Scanner import java.util.*; public class BetterRead { public static void main(string[] args) { Scanner stdin = new Scanner(SimpleRead.input); System.out.println("What is your name?"); String name = stdin.nextline(); System.out.println(name); System.out.println( "How old are you? What is your favorite double?"); System.out.println("(input: <age> <double>)"); int age = stdin.nextint(); double favorite = stdin.nextdouble(); System.out.println(age); System.out.println(favorite); System.out.format("Hi %s.\n", name); System.out.format("In 5 years you will be %d.\n", age + 5); System.out.format("My favorite double is %f.", favorite / 2); >> What is your name? Sir Robin of Camelot How old are you? What is your favorite double? (input: <age> <double>) Hi Sir Robin of Camelot. In 5 years you will be 27. My favorite double is

20 Scanner delimiters import java.util.*; public class ScannerDelimiter { public static void main(string[] args) { Scanner scanner = new Scanner("12, 42, 78, 99, 42"); scanner.usedelimiter("\\s*,\\s*"); while(scanner.hasnextint()) System.out.println(scanner.nextInt()); >>

21 StringTokenizer StringTokenizer Before regular expressions (in J2SE1.4) or the Scanner class (in Java SE5) the way to split a string into parts was to "tokenize" But now it s much easier and more succinct to do the same thing with regular expressions or the Scanner class.

22 StringTokenizer import java.util.*; public class ReplacingStringTokenizer { public static void main(string[] args) { String input = "But I m not dead yet! I feel happy!"; StringTokenizer stoke = new StringTokenizer(input); while(stoke.hasmoreelements()) System.out.print(stoke.nextToken() + " "); System.out.println(); System.out.println(Arrays.toString(input.split(" "))); Scanner scanner = new Scanner(input); while(scanner.hasnext()) System.out.print(scanner.next() + " "); >> But I m not dead yet! I feel happy! [But, I m, not, dead, yet!, I, feel, happy!] But I m not dead yet! I feel happy!

23 Arrays Most efficient way to hold references to objects Limitation: size of an array is fixed Benefits Array knows what type it holds, compile-time type checking Knows its size, you can ask

24 Returning an Array Returning Java array == returning a reference Reference knows the type of the array Doesn t matter where or how array is created Array is around as long as needed, GC cleans up

25 Arrays of Primitives Arrays can hold primitive types directly Containers can only hold references Can use wrapper classes to put primitives into containers, but that s read only

26 java.util.arrays Algorithms for array processing: binarysearch( ) equals( ) fill( ) The same object duplicated sort( ) Unstable Quicksort for primitives Stable merge sort for Objects Overloaded for Object and all primitives

27 Sorting No support for sorting in Java 1.0/1.1 Explain this one to me. They forgot?? Your class must implement Comparable Single method, compareto(object rv) Negative value if the argument is less than the current object Zero if the argument is equal Positive if the argument is greater

28 Imposing a Different Order If a class doesn t implement Comparable or you d like a different order Create a Comparator class Two methods, compare( ) and equals( ) Don't have to implement equals( ) except for special performance needs Just use the default Object equals( ) The compare( ) method must return a negative integer, zero, or a positive integer if the first argument is less than, equal to, or greater than the second, respectively Primitives can only sort in ascending order

29 Containers Divides the issue of "holding your objects": 1. Collection: a group of individual elements, often with some rule applied to them List holds elements in a particular sequence Set has no duplicates 2. Map: a group of key-value object pairs Can return a Set of its keys A Collection of its values Set of its pairs Maps can easily be expanded to multiple dimensions

30 Unlike arrays, built-in functionality Example introduces basic container types Printing containers >> [dog, dog, cat] [cat, dog] {cat=rags, dog=spot import java.util.*; public class PrintingContainers { static Collection fill(collection c) { c.add("dog"); c.add("dog"); c.add("cat"); return c; static Map fill(map m) { m.put("dog", "Bosco"); m.put("dog", "Spot"); m.put("cat", "Rags"); return m; public static void main(string[] args) { System.out.println(fill(new ArrayList())); System.out.println(fill(new HashSet())); System.out.println(fill(new HashMap())); ///:~

31 Filling Containers Containers.fill( ) duplicates a single object into the container Still a problem to add interesting data Will use another generator For Maps, it needs to produce an object containing two objects: Pair

32 Container Disadvantage Unknown type Containers all hold Object, so they hold anything Collection of Cat will also hold a Dog Casting back to the correct type Throwing an exception ; if you try to cast to the wrong type problem because you don t know until the program is running

33 Printing containers //: c09:cat.java public class Cat { private int catnumber; Cat(int i) { catnumber = i; void print() { System.out.println("Cat #" + catnumber); ///:~ //: c09:dog.java public class Dog { private int dognumber; Dog(int i) { dognumber = i; void print() { System.out.println("Dog #" + dognumber); ///:~ //: c09:catsanddogs.java // Simple container example. import java.util.*; public class CatsAndDogs { public static void main(string[] args) { ArrayList cats = new ArrayList(); for(int i = 0; i < 7; i++) cats.add(new Cat(i)); // Not a problem to add a dog to cats: cats.add(new Dog(7)); for(int i = 0; i < cats.size(); i++) ((Cat)cats.get(i)).print(); // Dog is detected only at run-time ///:~

34 The abstraction Iterators selecting each element in a sequence (traverse a Collection) Possibly make many iterators, and select more than one element at a time Hides underlying collection, so you can easily change from one type to another A design pattern

35 Iterators import java.util.*; class Hamster { private int hamsternumber; Hamster(int i) { hamsternumber = i; public String tostring() { return "This is Hamster #" + hamsternumber; class Printer { static void printall(iterator e) { while(e.hasnext()) System.out.println(e.next()); public class HamsterMaze { public static void main(string[] args) { ArrayList v = new ArrayList(); for(int i = 0; i < 3; i++) v.add(new Hamster(i)); Printer.printAll(v.iterator()); ///:~

36 Container Taxonomy

37 The Collection Interface boolean add(object) boolean addall(collection) void clear( ) boolean contains(object) boolean containsall(collection) boolean isempty( ) Iterator iterator( ) boolean remove(object) boolean removeall(collection) boolean retainall(collection) int size( ) Object[ ] toarray( ) Object[ ] toarray(object[ ] a)

38 Lists have additional abilities void add(index, Object) boolean addall(index, Collection) Object get(index) int indexof(object) int lastindexof(object) ListIterator listiterator() ListIterator listiterator(index) Object remove(index) Object set(index, Object) // Means: replace List sublist(fromindex, toindex)

39 Lists produce ListIterators boolean hasnext() Object next() boolean hasprevious() Object previous() int nextindex() int previousindex() add(object) void remove() void set(object) // Replace

40 ArrayList ArrayList & LinkedList Default choice for a simple sequence Optimal for rapid random access ListIterator should be used only for back-and-forth traversal of an ArrayList, but not for inserting and removing elements LinkedList Optimal sequential access with inexpensive insertions and deletions from the middle of the list possibly be used as a stack, a queue, and a deque addfirst( ), addlast( ), getfirst( ), getlast( ), removefirst( ), and removelast( ) ListIterator can be used for insertion and removal

41 Queues, Stacks and Deques Not there Use LinkedList addfirst( ), addlast( ) removefirst( ), removelast( ) getfirst( ), getlast( )

42 Sets Mathematical set abstraction No duplicates Two interfaces Set (identical to Collection) SortedSet Implementations HashSet for maximally fast lookups TreeSet to maintain sorted order Order determined by Comparable or Comparator) You can extract an ordered sequence from a TreeSet: Comparator comparator() Object first() Object last() SortedSet subset(fromelement, toelement) SortedSet headset(toelement) SortedSet tailset(fromelement)

43 Sets import java.util.*; import com.bruceeckel.util.*; public class Set1 { static Collections2.StringGenerator gen = Collections2.countries; public static void testvisual(set a) { Collections2.fill(a, gen.reset(), 10); Collections2.fill(a, gen.reset(), 10); Collections2.fill(a, gen.reset(), 10); System.out.println(a); // No duplicates! // Add another set to this one: a.addall(a); a.add("one"); a.add("one"); a.add("one"); System.out.println(a); // Look something up: System.out.println("a.contains(\"one\"): " + a.contains("one")); public static void main(string[] args) { System.out.println("HashSet"); testvisual(new HashSet()); System.out.println("TreeSet"); testvisual(new TreeSet()); ///:~

44 Maps Alternately termed a map, a dictionary or an associative array Like an ArrayList, but instead of using an integral index to look something up, another object is used as a key Store key/value pairs of Objects Duplicate Keys not allowed Returns keys as a Set view Returns values as a Collection

45 TreeMap SortedMap with elements stored in a tree Comparator comparator( ) Object firstkey( ) Object lastkey( ) SortedMap submap(fromkey, tokey) SortedMap headmap(tokey) SortedMap tailmap(fromkey) Viewing keys or pairs will be in sorted order Order determined by Comparable or Comparator

46 HashMap HashMap a Map with very fast lookup: uses a hash code to organize the objects Should typically be your first choice for a Map Program counts occurrences of random numbers:

47 HashMap import java.util.*; class Counter { int i = 1; public String tostring() { return Integer.toString(i); >> {19=526, 18=533, 17=460, 16=513, 15=521, 14=495, 13=512, 12=483, 11=488, 10=487, 9=514, 8=523, 7=497, 6=487, 5=480, 4=489, 3=509, 2=503, 1=475, 0=505 public class Statistics { public static void main(string[] args) { HashMap hm = new HashMap(); for(int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: Integer r = new Integer((int)(Math.random() * 20)); if(hm.containskey(r)) ((Counter)hm.get(r)).i++; else hm.put(r, new Counter()); System.out.println(hm); ///:~

48 HashMap key classes A common pitfall if a class is to be used as a key for a HashMap, you must override hashcode( ) and equals( ) from the common root class Object

49 Old 1.0/1.1 Containers They ll appear in older standard libraries And sometimes new ones Don t use them in new code Vector -> ArrayList BitSet (maybe use) Stack -> LinkedList Hashtable -> Map

50 Enumeration: old Iterator Smaller interface than Iterator, longer method names nextelement( ) moves to and produces the next item hasmoreelements( ) indicates the end Can actually appear quite a bit, even in new library code Treat it just like an Iterator without a remove( ) method

51 Summary Array associates numerical indices to objects Holds objects of a known type Fixed size

52 Summary Sequence (List) associates numerical indices to objects Only holds Object references Automatically resizes itself Set only holds one of each object HashSet for speed, TreeSet for sorted order Map associates objects with other objects Provides rapid random access HashMap orders with hashcode( ) & equals( ) TreeMap keeps sorted order

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University C O P Y R I G H T S 2 0 1 5 E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D - Containers - About Containers

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

Strings and Arrays. Hendrik Speleers

Strings and Arrays. Hendrik Speleers Hendrik Speleers Overview Characters and strings String manipulation Formatting output Arrays One-dimensional Two-dimensional Container classes List: ArrayList and LinkedList Iterating over a list Characters

More information

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1 COMP209 Object Oriented Programming Container Classes 3 Mark Hall List Functionality Types List Iterator Adapter design pattern Adapting a LinkedList to a Stack/Queue Map Functionality Hashing Performance

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data 1 JAVA PROGRAMMERS GUIDE LESSON 1 File: JGuiGuideL1.doc Date Started: July 10, 2000 Last Update: Jan 2, 2002 Status: proof DICTIONARIES, MAPS AND COLLECTIONS We have classes for Sets, Lists and Maps and

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

Java Collections Framework: Interfaces

Java Collections Framework: Interfaces Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

Sets and Maps. Part of the Collections Framework

Sets and Maps. Part of the 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 int size( ); boolean isempty( ); boolean contains(object

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Tha Java Programming Language

Tha Java Programming Language Tha Java Programming Language Kozsik Tamás (2000-2001) kto@elte.hu http://www.elte.hu/~k to/ III. Arrays, collections and other baseclasses Some of the baseclasses Object String StringBuffer Integer, Double,...

More information

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Wrapper classes. Wrapper classes Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

Java Collections. Engi Hafez Seliem

Java Collections. Engi Hafez Seliem Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description java.lang Interface Iterable Type Parameters: T - the type of elements returned by the iterator Iterator iterator() Returns an iterator over a set of elements of type T. java.util Interface Iterator

More information

COMP6700/2140 Abstract Data Types: Queue, Set, Map

COMP6700/2140 Abstract Data Types: Queue, Set, Map COMP6700/2140 Abstract Data Types: Queue, Set, Map Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 19 April 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140

More information

Object-Oriented Programming with Java

Object-Oriented Programming with Java Object-Oriented Programming with Java Recitation No. 2 Oranit Dror The String Class Represents a character string (e.g. "Hi") Explicit constructor: String quote = "Hello World"; string literal All string

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

The Java Collections Framework and Lists in Java Parts 1 & 2

The Java Collections Framework and Lists in Java Parts 1 & 2 The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering

More information

Collections (Java) Collections Framework

Collections (Java) Collections Framework Collections (Java) https://docs.oracle.com/javase/tutorial/collections/index.html Collection an object that groups multiple elements into a single unit. o store o retrieve o manipulate o communicate o

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Collections Framework: Part 2

Collections Framework: Part 2 Collections Framework: Part 2 Computer Science and Engineering College of Engineering The Ohio State University Lecture 18 Collection Implementations Java SDK provides several implementations of Collection

More information

An Interface with Generics

An Interface with Generics Generics CSC207 Software Design Generics An Interface with Generics Generics class foo introduces a class with a type parameter T. introduces a type parameter that is required to be

More information

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock) Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Computer Science II (Spring )

Computer Science II (Spring ) Computer Science II 4003-232-01 (Spring 2007-2008) Week 5: Generics, Java Collection Framework Richard Zanibbi Rochester Institute of Technology Generic Types in Java (Ch. 21 in Liang) What are Generic

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

Lists using LinkedList

Lists using LinkedList Lists using LinkedList 1 LinkedList Apart from arrays and array lists, Java provides another class for handling lists, namely LinkedList. An instance of LinkedList is called a linked list. The constructors

More information

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList This article discusses the main classes of Java Collection API. The following figure demonstrates the Java Collection framework. Figure

More information

CS Programming Language Java. Fall 2004 Sept. 29

CS Programming Language Java. Fall 2004 Sept. 29 CS3101-3 Programming Language Java Fall 2004 Sept. 29 Road Map today Java review Homework review Exception revisited Containers I/O What is Java A programming language A virtual machine JVM A runtime environment

More information

A simple map: Hashtable

A simple map: Hashtable Using Maps A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put(key, value); To retrieve a value from

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

Java Collections Framework reloaded

Java Collections Framework reloaded Java Collections Framework reloaded October 1, 2004 Java Collections - 2004-10-01 p. 1/23 Outline Interfaces Implementations Ordering Java 1.5 Java Collections - 2004-10-01 p. 2/23 Components Interfaces:

More information

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

Chapter 5 Java Collection. Wang Yang

Chapter 5 Java Collection. Wang Yang Chapter 5 Java Collection Wang Yang wyang@njnet.edu.cn Outline Last Chapter Review Array & Arrays Tourism Collection & Collections Map Performance benchmark Last Chapter Review Exception Exception is an

More information

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code. Lecture 15 Summary Collections Framework Iterable, Collections, Set Map Collections class Comparable and Comparator By the end of this lecture, you will be able to use different types of Collections and

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc. Contents Topic 08 - Collections I. Introduction - Java Collection Hierarchy II. Choosing/using collections III. Collection and Iterator IV. Methods of Collection V. Concrete classes VI. Implementation

More information

Generics and collections

Generics and collections Generics From JDK 1.5.0 They are similar to C++ templates They allow to eliminate runtime exceptions related to improper casting (ClassCastException) Traditional approach public class Box { private Object

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology Lists and Iterators CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology Announcements Should be making progress on VectorGraphics. Should have turned in CRC cards,

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

Notes on access restrictions

Notes on access restrictions Notes on access restrictions A source code file MyClass.java is a compilation unit and can contain at most one public class. Furthermore, if there is a public class in that file, it must be called MyClass.

More information

CSC 321: Data Structures. Fall 2013

CSC 321: Data Structures. Fall 2013 CSC 321: Data Structures Fall 2013 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

CSE 143 Au03 Final Exam Page 1 of 15

CSE 143 Au03 Final Exam Page 1 of 15 CSE 143 Au03 Final Exam Page 1 of 15 Reference information about many standard Java classes appears at the end of the test. You might want to tear off those pages to make them easier to refer to while

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

Collection Framework Collection, Set, Queue, List, Map 3

Collection Framework Collection, Set, Queue, List, Map 3 Collection Framework Collection, Set, Queue, List, Map 3 1 1. Beginner - What is Collection? What is a Collections Framework? What are the benefits of Java Collections Framework? 3 2. Beginner - What is

More information

Generic Programming. *Really* reusable code

Generic Programming. *Really* reusable code Generic Programming *Really* reusable code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers to create data structures

More information

An Introduction to Data Structures

An Introduction to Data Structures An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use

More information

JAVA. java.lang.stringbuffer java.lang.stringbuilder

JAVA. java.lang.stringbuffer java.lang.stringbuilder JAVA java.lang.stringbuffer java.lang.stringbuilder 1 Overview mutable string instances of String are immutable do not extend String String, StringBuffer, StringBuilder are final StringBuffer safe for

More information

Data Structures and Abstractions with Java

Data Structures and Abstractions with Java Global edition Data Structures and Abstractions with Java Fourth edition Frank M. Carrano Timothy M. Henry Data Structures and Abstractions with Java TM Fourth Edition Global Edition Frank M. Carrano University

More information

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14 MINI-MAX USING TREES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 Spring 2014 2 Important Dates. April 10 --- A4 due (Connect 4, minimax, trees) April 15 --- A5 due (Exercises on different topics,

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

CSC 321: Data Structures. Fall 2012

CSC 321: Data Structures. Fall 2012 CSC 321: Data Structures Fall 2012 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

Fundamental language mechanisms

Fundamental language mechanisms Java Fundamentals Fundamental language mechanisms The exception mechanism What are exceptions? Exceptions are exceptional events in the execution of a program Depending on how grave the event is, the program

More information

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5 CSCI 6234 Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship George Blankenship 1 Java Topics Running Java programs Stream I/O New features George Blankenship 2 Running

More information

To describe the Java Collections Framework. To use the Iterator interface to traverse a. To discover the Set interface, and know how

To describe the Java Collections Framework. To use the Iterator interface to traverse a. To discover the Set interface, and know how Chapter 22 Java Collections Framework :Objectives To describe the Java Collections Framework hierarchy To use the Iterator interface to traverse a collection To discover the Set interface, and know how

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

11. Collections of Objects

11. Collections of Objects 11. Collections of Objects 1 Arrays There are three issues that distinguish arrays from other types of containers: efficiency, type, and the ability to hold primitives. When you re solving a more general

More information

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces Taking Stock IE170: Algorithms in Systems Engineering: Lecture 7 Jeff Linderoth Department of Industrial and Systems Engineering Lehigh University January 29, 2007 Last Time Practice Some Sorting Algs

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 16 References and linked nodes reading: 16.1 2 Value semantics value semantics: Behavior where values are copied when assigned, passed as parameters, or returned. All primitive

More information

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com 2 Disclaimer & Acknowledgments Even though Sang Shin is a full-time employee

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net Sorting Tree Balancing A sorted tree is balanced iff for each node holds: Math.abs(size(node.left)

More information

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Implementations I 1 Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Stack and queues Array-based implementations

More information

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started Application Development in JAVA Duration Lecture: Specialization x Hours Core Java (J2SE) & Advance Java (J2EE) Detailed Module Part I: Core Java (J2SE) Getting Started What is Java all about? Features

More information

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/

More information

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

Interfaces, collections and comparisons

Interfaces, collections and comparisons תכנות מונחה עצמים תרגול מספר 4 Interfaces, collections and comparisons Interfaces Overview Overview O Interface defines behavior. Overview O Interface defines behavior. O The interface includes: O Name

More information

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction

More information

Building Java Programs

Building Java Programs Building Java Programs A Back to Basics Approach Stuart Reges I Marty Stepp University ofwashington Preface 3 Chapter 1 Introduction to Java Programming 25 1.1 Basic Computing Concepts 26 Why Programming?

More information

CS 307 Final Spring 2008

CS 307 Final Spring 2008 Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2008 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to

More information

Collections and Maps

Collections and Maps Software and Programming I Collections and Maps Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Array Lists Enhanced for Loop ArrayList and LinkedList Collection Interface Sets and

More information

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel) Programmieren II Collections Alexander Fraser fraser@cl.uni-heidelberg.de (Based on material from T. Bögel) May 28, 2014 1 / 46 Outline 1 Recap Paths and Files Exceptions 2 Collections Collection Interfaces

More information

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

boolean add(object o) Method Description (from docs API ) Method Description (from docs API ) Interface Collection Method Description (from docs API ) boolean add(object o) boolean addall(collection c) void clear() ensures that this collection contains the specified element adds all of the elements

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net MULTIVARIATE TREES 2 Multivariate Trees general class of trees nodes can have any number of children

More information

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String. CMSC 131: Chapter 21 (Supplement) Miscellany Miscellany Today we discuss a number of unrelated but useful topics that have just not fit into earlier lectures. These include: StringBuffer: A handy class

More information

Pieter van den Hombergh Richard van den Ham. February 8, 2018

Pieter van den Hombergh Richard van den Ham. February 8, 2018 Pieter van den Hombergh Richard van den Ham Fontys Hogeschool voor Techniek en Logistiek February 8, 2018 /FHTenL February 8, 2018 1/16 Collection Zoo The basic collections, well known in programming s

More information

Get started with the Java Collections Framework By Dan Becker

Get started with the Java Collections Framework By Dan Becker Get started with the Java Collections Framework By Dan Becker JavaWorld Nov 1, 1998 COMMENTS JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework. "Oh no,"

More information

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017 Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek June 8, 2017 /FHTenL June 8, 2017 1/19 Collection Zoo The basic collections, well known in programming s

More information

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1 CS61B Lecture #17 Last modified: Mon Oct 1 13:40:29 2018 CS61B: Lecture #17 1 Topics Overview of standard Java Collections classes Iterators, ListIterators Containers and maps in the abstract Amortized

More information

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so. CSE 143 Sp04 Midterm 2 Page 1 of 10 Reference information about some standard Java library classes appears on the last pages of the test. You can tear off these pages for easier reference during the exam

More information

Practical Session 3 Java Collections

Practical Session 3 Java Collections Practical Session 3 Java Collections 1 Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack Maps The Collections class Wrapper classes 2 Collection

More information

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 MID YEAR COMP103 Introduction to Data

More information

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections Course Name: Advanced Java Lecture 8 Topics to be covered Collections Introduction A collection, sometimes called a container, is simply an object that groups multiple elements into a single unit. Collections

More information

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 22 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information