46
1 Collections, Ant, Collections, Ant, Subversion Subversion James Atlas James Atlas June 26, 2008 June 26, 2008

1 Collections, Ant, Subversion James Atlas June 26, 2008

Embed Size (px)

Citation preview

Page 1: 1 Collections, Ant, Subversion James Atlas June 26, 2008

11

Collections, Ant, SubversionCollections, Ant, Subversion

James AtlasJames Atlas

June 26, 2008June 26, 2008

Page 2: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 22

ReviewReview

• I/O: StreamsI/O: Streams

• CloningCloning

Page 3: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 33

A More Connected StreamA More Connected Stream

• FileInputStream reads bytes from the fileFileInputStream reads bytes from the file• BufferedInputStream buffers bytesBufferedInputStream buffers bytes

speeds up access to the file.speeds up access to the file.

• DataInputStream reads buffered bytes as typesDataInputStream reads buffered bytes as types

FileInputStream DataInputStream

double

char

file BufferedInputStream

Page 4: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 44

FYI: Additional I/O FunctionalityFYI: Additional I/O Functionality

• Java provides classes so that you canJava provides classes so that you can Lock files (Lock files (java.nio.channels.FileLockjava.nio.channels.FileLock))

• Coordinates accesses to filesCoordinates accesses to files Multiple programs read/write same fileMultiple programs read/write same file

• Depends on OS to enforce locksDepends on OS to enforce locks Read from random points in the fileRead from random points in the file• java.io.RandomAccessFilejava.io.RandomAccessFile

Page 5: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 55

Parsing FilesParsing Files

• Use programs to automate tasksUse programs to automate tasks

• Often have large amounts of data in filesOften have large amounts of data in files

• Java provides classes to make parsing Java provides classes to make parsing easiereasier

Page 6: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 66

String classString class

String test = “this is a test”;String[] result = test.split("\\s");for (int x=0; x<result.length; x++) System.out.println(result[x]);

Regular expression: \\s means whitespace

thisisatest

Output:

Page 7: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 77

Object CloningObject Cloning• To make a new object, clone the objectTo make a new object, clone the object

clone starts in the same state as the current object but is a clone starts in the same state as the current object but is a different objectdifferent object

difference with Serialization?difference with Serialization?

Chicken copy = (Chicken)original.clone();copy.feed();// original remained unchanged (hasn’t eaten)

Page 8: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 88

The Problem with CloningThe Problem with Cloning

Gregorian Calendar-----------------------

Chicken-----------------------name: weight: birthdate:

Chicken-----------------------name: weight: birthdate:

Foggy

Foggy

10

10

original

clone

Page 9: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 99

Object CloningObject Cloning

• Default: class should not be cloned Default: class should not be cloned • To clone:To clone:

The class must implement the The class must implement the CloneableCloneable interfaceinterface• Marker interface Marker interface

The class must The class must redefineredefine the the cloneclone() method () method with the with the publicpublic access modifier access modifier• allows objects to be cloned by any class/objectallows objects to be cloned by any class/object• you can make an overridden method less private

but not more private

Page 10: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1010

TodayToday

• Java Java CollectionsCollections

• AntAnt

• SubversionSubversion

Page 11: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1111

CollectionsCollections

Page 12: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1212

CollectionsCollections• Similar to C++ Standard Template Library

• Also known as Also known as ContainersContainers

• group multiple elements into a single unit

• store, retrieve, manipulate, and communicate aggregate data

• represent data items that form a natural group poker hand (a collection of cards) mail folder (a collection of letters) telephone directory (a mapping of names to phone

numbers).

• Examples: Hashtables, Sets, Vector

Page 13: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1313

Collections FrameworkCollections Framework

• a unified architecture for representing and manipulating collections

• More than arraysMore flexible, functionality, dynamic sizing

• java.util

Page 14: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1414

Collections FrameworkCollections Framework• Interfaces

abstract data types that represent collections collections can be manipulated independently of

implementation

• Implementations concrete implementations of the collection interfaces reusable data structures

• Algorithms methods that perform useful computations on collections,

e.g., searching and sorting polymorphic: same method can be used on many different

implementations of the appropriate collection interface reusable functionality

Page 15: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1515

Core Collection InterfacesCore Collection Interfaces

• Encapsulate different types of collectionsEncapsulate different types of collections

Page 16: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1616

Generic Collection InterfacesGeneric Collection Interfaces• New to 1.5: Generic Collections

declaration of the Collection interface:

public interface Collection<E>...

Page 17: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1717

Generic Collection InterfacesGeneric Collection Interfaces• New to 1.5: Generic Collections

declaration of the Collection interface:

public interface Collection<E>...• <E> means interface is generic for element class

• specify the type of object when declare a Collection allows the compiler to verify that the type of object you

put into the collection is correct• reduces errors at runtime

• Example, a hand of cardsList<Card> hand = new List<Card>();List<Card> hand = new List<Card>();

Make sure put in, get out appropriate typeMake sure put in, get out appropriate type

Page 18: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1818

ListList Interface Interface• An ordered collection of elementsAn ordered collection of elements• Can contain duplicate elementsCan contain duplicate elements• Has control over where objects are stored in the listHas control over where objects are stored in the list• boolean add(Object o)boolean add(Object o)

Boolean so that List can refuse some elementsBoolean so that List can refuse some elements• e.g., refuse adding null elementse.g., refuse adding null elements

• Object get(int index)Object get(int index) Returns elements at the position indexReturns elements at the position index

• int size() int size() Returns the number of elements in the listReturns the number of elements in the list

• And more! (contains, remove, toArray, …)And more! (contains, remove, toArray, …)

Page 19: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 1919

ListList Implementations Implementations

•ArrayListArrayList Resizable arrayResizable array Used most frequentlyUsed most frequently FastFast

•LinkedListLinkedList Use if adding elements to beginning of listUse if adding elements to beginning of list Use of often delete from middle of listUse of often delete from middle of list

cards.Deal.java

Page 20: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2020

Implementation vs. InterfaceImplementation vs. Interface• Implementation choice affects only performance

• Preferred style choose an implementation assign the new collection to a variable of the

corresponding interface type• or pass the collection to a method expecting an argument

of the interface type

• Why?

Page 21: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2121

Implementation vs. InterfaceImplementation vs. Interface• Implementation choice affects only performance

• Preferred style choose an implementation assign the new collection to a variable of the

corresponding interface type• or pass the collection to a method expecting an argument

of the interface type

• Why? Program does not depend on methods in a given

implementation Programmer can change implementations

• performance concerns or behavioral details

Page 22: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2222

SetSet Interface Interface• No duplicate elementsNo duplicate elements

Needs to be able to determine if two elements are Needs to be able to determine if two elements are “logically” the same (“logically” the same (equalsequals method) method)

• Models mathematical set abstractionModels mathematical set abstraction• boolean add(Object o)boolean add(Object o)

Boolean so that Set can refuse some elementsBoolean so that Set can refuse some elements• e.g., refuse adding null elementse.g., refuse adding null elements

• int size() int size() Returns the number of elements in the listReturns the number of elements in the list

• Note: no get method -- get #3 from the set?Note: no get method -- get #3 from the set?

• And more! (contains, remove, toArray, …)And more! (contains, remove, toArray, …)

Page 23: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2323

SetSet Implementations Implementations• HashSetHashSet

Hash tableHash table Used more frequentlyUsed more frequently Faster than TreeSetFaster than TreeSet No orderingNo ordering

• TreeSetTreeSet TreeTree SortsSorts

FindDuplicates.java

Page 24: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2424

MapMap Interface Interface

• Maps keys to valuesMaps keys to values• No duplicate keysNo duplicate keys

Each key maps to at most one valueEach key maps to at most one value

•Object put(Object key, Object Object put(Object key, Object value)value) Returns old value that key mapped toReturns old value that key mapped to

•Object get(Object key)Object get(Object key) Returns value at that keyReturns value at that key

•Set keySet() Set keySet() Returns the set of keysReturns the set of keys

Page 25: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2525

MapMap Implementations Implementations

• HashMapHashMap FastFast

• TreeMapTreeMap SortingSorting Key-ordered iterationKey-ordered iteration

• LinkedHashMapLinkedHashMap FastFast Insertion-order iterationInsertion-order iteration Remove stale mappings --> custom cachingRemove stale mappings --> custom caching

Page 26: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2626

Declaring MapsDeclaring Maps

• Declare types for both keys and valuesDeclare types for both keys and values•Class HashMap<K,V>

Map<String, List<String>> map Map<String, List<String>> map

= new HashMap<String, List<String>>();= new HashMap<String, List<String>>();

Keys are StringsValues are Lists of Strings

Page 27: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2727

Traversing Collections (1)Traversing Collections (1)

• For-each loop:For-each loop:for (Object o : collection)

System.out.println(o);

• Equivalent to:Equivalent to:for (Iterator i = collection.iterator(); i.hasNext();) {

Object o = i.next();

System.out.println(o);

}

Page 28: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2828

Traversing Collections: IteratorsTraversing Collections: Iterators• Java Interface Java Interface

• Same idea as C++ iteratorsSame idea as C++ iterators• Object next()Object next()

get the next elementget the next element

• boolean hasNext()boolean hasNext() are there more elements?are there more elements?

• void remove()void remove() remove the previous elementremove the previous element Only Only safesafe way to remove elements during iteration way to remove elements during iteration

Page 29: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 2929

Iterator: Like a CursorIterator: Like a Cursor

• Always between two elementsAlways between two elements

Page 30: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3030

Polymorphic Filter AlgorithmPolymorphic Filter Algorithm

static void filter(Collection c) {

Iterator i = c.iterator();

while( i.hasNext() ) {

// if the next element does not

// adhere to the condition, remove it

if (!cond(i.next())) {

i.remove();

}

}

}

Page 31: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3131

Traversing Lists: List IteratorTraversing Lists: List Iterator

• Methods to traverse list backwardsMethods to traverse list backwards listIterator(int position)listIterator(int position) Pass in size() as index to get at end of listPass in size() as index to get at end of list hasPrevious()hasPrevious() previous()previous()

• Used for insertion/modification/deletion Used for insertion/modification/deletion in linked lists in the middlein linked lists in the middle

Page 32: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3232

EnumerationEnumeration

• Legacy classLegacy class

• Similar to IteratorSimilar to Iterator•boolean hasMoreElements() •Object nextElement() • Longer method names

• Doesn’t have remove operation

Page 33: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3333

Collection classes to avoidCollection classes to avoid

• Synchronized classesSynchronized classes For multiple threads sharing same collectionFor multiple threads sharing same collection Slow down typical programsSlow down typical programs Vector -> ArrayList, Hashtable -> HashMapVector -> ArrayList, Hashtable -> HashMap See java.util.concurrentSee java.util.concurrent

Page 34: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3434

Utility Class: CollectionsUtility Class: Collections

• Similar to Similar to ArraysArrays class class

• Contains methods forContains methods for Binary searchingBinary searching SortingSorting Min/max finding (“extremes”)Min/max finding (“extremes”) ReversingReversing ShufflingShuffling ……

Page 35: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3535

Localization/InternationalizationLocalization/Internationalization

• Part of java.utilPart of java.util

• Customize how data is presented and Customize how data is presented and formattedformatted

• Use Locale objectsUse Locale objects Specify language, geographic regionSpecify language, geographic region

• Calendar, GregorianCalendarCalendar, GregorianCalendar

• CurrencyCurrency

• DateDate

• TimeZoneTimeZone

Page 36: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3636

Compression: Compression: java.util.zipjava.util.zip

• GZIP compressionGZIP compression GZIPInputStreamGZIPInputStream GZIPOutputStreamGZIPOutputStream Standard filtered streamStandard filtered stream

• you don't do anything special!you don't do anything special!

• ZIP compressionZIP compression ZipInputStreamZipInputStream ZipOutputStreamZipOutputStream

Page 37: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3737

AntAnt

• Java-based build toolJava-based build tool

• Similar to Similar to make, gnumake, jam, etcmake, gnumake, jam, etc

• XML-basedXML-based

• Platform independentPlatform independent

• http://ant.apache.org/http://ant.apache.org/

Page 38: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3838

Sample Ant ScriptSample Ant Script<project name="diihard" default="default">

<property name="src" location="src"/>

<path id="compile.classpath">

<fileset dir="${basedir}/lib">

<include name="adopt.zip"/>

<include name="commons-collections-3.2.jar"/>

...

</fileset>

</path>

<target name="default">

<javac srcdir="${dist.src.java}"

destdir="${dist}/${tstamp}/classes">

<classpath refid="compile.classpath"/>

</javac>

</target>

<target name="william_yeoh" depends="default"/>

</project>

Page 39: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 3939

Other Ant “tasks”Other Ant “tasks”

• Antcall - call a specific target taskAntcall - call a specific target task

• Copy - copy files/directories etc.Copy - copy files/directories etc. Mkdir/move/delete/etcMkdir/move/delete/etc

• Exec - execute a platform specific taskExec - execute a platform specific task

• Parallel - execute tasks in parallelParallel - execute tasks in parallel

• Java/Javac - execute/compile Java codeJava/Javac - execute/compile Java code

• Jar/Tar/Zip/etc. - archiving tasksJar/Tar/Zip/etc. - archiving tasks

• And many many more; custom tasksAnd many many more; custom tasks

Page 40: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4040

Ant Integration with EclipseAnt Integration with Eclipse

Page 41: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4141

SubversionSubversion

• Client/Server Version Control systemClient/Server Version Control system

• http://subversion.tigris.org/http://subversion.tigris.org/

• Why use a Version Control system?Why use a Version Control system?

Page 42: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4242

SubversionSubversion

• Client/Server Version Control systemClient/Server Version Control system

• http://subversion.tigris.org/http://subversion.tigris.org/

• Why use a Version Control system?Why use a Version Control system? Track history of changesTrack history of changes Concurrent modification of projectsConcurrent modification of projects

• Subversion is a successor to CVSSubversion is a successor to CVS Atomic commitsAtomic commits Renamed/copied/moved/removed files retain historyRenamed/copied/moved/removed files retain history Branching/tagging are cheap operationsBranching/tagging are cheap operations

Page 43: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4343

Subversion basicsSubversion basics

• Check-out/Commit/Update codeCheck-out/Commit/Update code

• BranchBranch A copy of the codeA copy of the code

• TagTag A label of specific code revisionsA label of specific code revisions

Page 44: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4444

Subversion Integration with Subversion Integration with Eclipse - SubclipseEclipse - Subclipse• http://subclipse.tigris.org/http://subclipse.tigris.org/

• Can install by going to Help->Software Can install by going to Help->Software UpdatesUpdates Create a new remote site with Create a new remote site with

http://subclipse.tigris.org/update_1.4.x for the http://subclipse.tigris.org/update_1.4.x for the URLURL

Download/install Subclipse and JavaHL native Download/install Subclipse and JavaHL native librarylibrary

Page 45: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4545

3 Week Checklist3 Week Checklist

• Primitive typesPrimitive types• Object-oriented conceptsObject-oriented concepts• I/OI/O• CollectionsCollections• Serialization/CloningSerialization/Cloning• Common toolsCommon tools

Eclipse/Ant/SubversionEclipse/Ant/Subversion

• Your job: representing data, leverage classesYour job: representing data, leverage classes

Page 46: 1 Collections, Ant, Subversion James Atlas June 26, 2008

June 26, 2008June 26, 2008 James Atlas - CISC370James Atlas - CISC370 4646

Assignment 3Assignment 3

• Applying streams and collections to your Applying streams and collections to your media librarymedia library

• Code submissionCode submission New versions of your classes --> New packageNew versions of your classes --> New package