Tony Valderrama, SIPB IAP 2010

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

CONTAİNERS COLLECTİONS

Fundamental language mechanisms

Generics Collection Framework

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

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

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

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.

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Algorithms. Produced by. Eamonn de Leastar

Collections Framework: Part 2

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

Class 32: The Java Collections Framework

Introduction to Programming Using Java (98-388)

CS Ananda Gunawardena

Sets and Maps. Part of the Collections Framework

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

CSC 1214: Object-Oriented Programming

CMSC 202. Containers

Computer Science II (Spring )

Advanced Programming Generics Collections

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Software 1 with Java. Recitation No. 6 (Collections)

JAVA. Duration: 2 Months

Programming Languages and Techniques (CIS120)

Topic 10: The Java Collections Framework (and Iterators)

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

JAVA Native Interface

An Interface with Generics

9/16/2010 CS Ananda Gunawardena

Core Java Contents. Duration: 25 Hours (1 Month)

Collections (Java) Collections Framework

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

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

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

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

Lecture 5 - NDK Integration (JNI)

What is the Java Collections Framework?

CSE 143 Au03 Final Exam Page 1 of 15

Java Input/Output. 11 April 2013 OSU CSE 1

EXAMINATIONS 2017 TRIMESTER 2

Java Native Interface. Diego Rodrigo Cabral Silva

Lecture 6 Collections

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

DM550 Introduction to Programming part 2. Jan Baumbach.

PIC 20A Collections and Data Structures

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

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

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

Java Collections Framework reloaded

Programming Languages and Techniques (CIS120)

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

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

Software Practice 1 - OOP (3) API

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

Invoking Native Applications from Java

Programming Languages and Techniques (CIS120)

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

JAVA SYLLABUS FOR 6 WEEKS

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

תוכנה 1 מבני נתונים גנריים

Collections Questions

Objec&ves. Review. Standard Error Streams

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Java Programming Unit 8. Selected Java Collec5ons. Generics.

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Object-Oriented Programming with Java

Objectives. Describe ways to create constants const readonly enum

CMSC 202H. Containers and Iterators

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

DM550 Introduction to Programming part 2. Jan Baumbach.

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

Parametric polymorphism and Generics

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

COMP 103 : Test. 2018, Sept 12//(Corrected)

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.

University of Maryland College Park Dept of Computer Science

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

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

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

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

EXAMINATIONS 2016 TRIMESTER 2

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

JAVA. 1. Introduction to JAVA

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM

CS2110: Software Development Methods. Maps and Sets in Java

Java Magistère BFA

Transcription:

Today Java API java.util java.io More OOP Generics Enum.jar files JNI Q & A Announcements Course website: http://sipb.mit.edu/iap/java/ Email: sipb-iap-java@mit.edu

package java.io Images from the Java Tutorial

I/O Streams socket file database byte array process data transform split buffer socket file database byte array // Always close your streams! try { // doprocessing finally { stream.close(); Images from The Java Tutorial

Byte streams Examples: CopyBytes.java, CopyCharacters.java, CopyLines.java

Other kinds of I/O Standard: System.in System.out System.err java.net.socket: socket.getinputstream() socket.getoutputstream() Serialization java.io.objectoutputstream java.io.objectinputstream

Interacting with the user // construct a java.io.bufferedreader BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); in.readline(); // CAREFUL! This only exists when java is started from the command line Console c = System.console(); c.readline(); char[] passwd; if ((passwd = c.readpassword("[%s]", "Password:"))!= null) { // verify password java.util.arrays.fill(passwd, ' '); // use java.util.scanner Scanner s = new Scanner(System.in); s.nextline(); s.next(); // next parsing token (word, by default)

package java.util Images from the Java Tutorial

Collection At the most abstract level, a group of Objects. package java.util; public interface Collection { public boolean add(object o); public void remove(object o); public boolean contains(object o); public int size(); // number of objects // returns true if it contains all elements in the given Collection. public boolean containsall(collection c); // adds all elements in the given Collection public boolean addall(collection c); // removes all elements in the given Collection from self. public boolean removeall(collection c); // removes all elements from the Collection. public void clear(); // and more...

Data Structures Each implementation is suited to a different situation: General-purpose Implementations Interfaces Implementations Hash table Resizable array Tree Linked list Hash table + Linked list Set HashSet TreeSet LinkedHashSet List ArrayList LinkedList Queue LinkedList Map HashMap TreeMap LinkedHashMap

Collections Allows abstract manipulation of collections. public class java.util.collections { public static Object min(list); public static Object max(list); public static void fill(object, List); public static void reverse(list); // guarantees n log(n) time --> optimized merge sort public static void sort(list); public static void shuffle(list); public static int frequency(object, Collection); public static boolean disjoint(collection, Collection); // and more...

ArrayList List l = new ArrayList(); l.add(2); l.add(3); l.add(1); Collections.sort(l); System.out.print(l.toString());

The problem with generic utilities List l = new ArrayList(); l.add(2); l.add(3); l.add(1); Collections.sort(l); // Data structure doesn t know what it holds at compile-time! // We have to cast, which breaks type safety Integer min = (Integer)l.get(0);

<Generics> to the rescue! package java.util; public interface List { public boolean add(object o); public Object get(); public int size(); // number of objects // adds all elements in the given Collection public boolean addall(collection c); // returns true if it contains all elements in the given Collection. public boolean containsall(collection c); // removes all elements in the given Collection from self. public boolean removeall(collection c); // removes all elements from the Collection. public void clear(); // and more...

<Generics> to the rescue! package java.util; public interface List<E> { public boolean add(e o); public E get(); public int size(); // number of objects // adds all elements in the given Collection public boolean addall(collection <? extends E> c); // and more... public interface Map<K,V> { public V put(k key, V value); public V get(k key); public void putall(map<? extends K,? extends V>);

Caveats... List<Integer> l = new ArrayList<Integer>(); l.add(1); l.add(2); // what if this were possible? List<Number> m = l; // this is perfectly valid m.clear(); m.add(math.pi); // uh oh! Integer i = l.get(0);

Wildcards List<?> ints = new ArrayList<Integer>() ints.add(0); ints.add(2); // valid List<?> list = ints; int size = list.size() // CAN'T DO THIS! Unkown type --> compile time error list.add(1); // bounded wildcards public <E> getrandomelement(list<? extends E> list){ return list.get((int)(math.random()*list.size()); public void insertelementrandomly(t element, List<? super T> list) { list.add(element, (int)(math.random()*list.size());

Type erasure public class MyClass<E> { public static void mymethod(object item) { if (item instanceof E) { //Compiler error E item2 = new E(); //Compiler error E[] iarray = new E[10]; //Compiler error E obj = (E)new Object(); //Unchecked cast warning public static void discoverclass(e item){ item.getclass(); // every Object can do this

Enums public class Day { public static final int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; private int day; public Day(int day){this.day = day; public boolean isweekend(){ switch (day) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: return true; case SATURDAY: case SUNDAY: default: return true;

Enums enum Day { SUNDAY(true), MONDAY(false), TUESDAY(false), WEDNESDAY(false), THURSDAY(false), FRIDAY(false), SATURDAY(true); public final boolean isweekend; // constructor Day(boolean isweekend){ this.isweekend = isweekend; Day d = Day.SUNDAY; boolean b = d.isweekend; switch(d){ case SUNDAY: //... case MONDAY: //... // if it's just to keep track of state enum ThreadState{ STOPPED, RUNNING, WAITING

C:\$> javac tvald\applet\animatedapplet.java C:\$> javac tvald\intro2java\examples\day4\demoapplet.java C:\$> jar cf DemoApplet.jar tvald\applet\animatedapplet.class tvald\int ro2java\examples\day4\demoapplet* C:\$> dir... tvald DemoApplet.jar To create a JAR file: To view contents: To extract contents: To run a JAR app: Applets from JARs: jar cf jar-file input-file(s) jar tf jar-file jar xf jar-file java jar app.jar <applet code="foo.class" archive="foo.jar"></applet>

http://java.sun.com/developer/onlinetraining/programming/jdcbook/jniexam p.html#comp native <type> name(args...); static { System.loadLibrary("nativelib"); // on the command line -> generates c/c++ header file $> javah -jni Foo.java /* Class: ReadFile * Method: loadfile * Signature: (Ljava/lang/String;)[B */ JNIEXPORT jbytearray JNICALL Java_ReadFile_loadFile (JNIEnv *, jobject, jstring,...); // implement this method in C or C++ // compile it with gcc as a dynamic or shared object library // stick it where LD_LIBRARY_PATH will find it $> java Foo