Intro to Java Week 3 Tuesday, November 11, 14 Homeworks 1&2 - - PowerPoint PPT Presentation

intro to java week 3
SMART_READER_LITE
LIVE PREVIEW

Intro to Java Week 3 Tuesday, November 11, 14 Homeworks 1&2 - - PowerPoint PPT Presentation

Intro to Java Week 3 Tuesday, November 11, 14 Homeworks 1&2 Review Hwk 1 Game, Taxi, Art, Hadamard Hwk 2 CSV , Rational/Complex, Stack Tuesday, November 11, 14 OOP Recap the class is the fundamental building block of Java consists of


slide-1
SLIDE 1

Intro to Java Week 3

Tuesday, November 11, 14

slide-2
SLIDE 2

Homeworks 1&2 Review

Hwk 1 Game, Taxi, Art, Hadamard Hwk 2 CSV , Rational/Complex, Stack

Tuesday, November 11, 14

slide-3
SLIDE 3

OOP Recap

the class is the fundamental building block of Java consists of a package, any number of data and method members, class or instance, and documentation class promote modularity by bundling several related things together a class can present a external interface without exposing internals by using access controls

Tuesday, November 11, 14

slide-4
SLIDE 4

OOP Recap

Java only supports “single inheritance”, but interfaces yield similar functionality without the complexity of “multiple inheritance” Error system in Java is based on a hierarchy of classes rooted in “Throwable” Classes promote code reuse thru composition(using existing classes as parts of new classes) and inheritance(extending the definition of a class to modify its behavior) Polymorphism - generally a subclass can be used anywhere a super class appears

Tuesday, November 11, 14

slide-5
SLIDE 5

Variable Number of Arguments

Any number of “required” args, followed by any number of “optional” args Optional args are collected into an array can do “printf” example: varargs

Tuesday, November 11, 14

slide-6
SLIDE 6

Need More Stacks!

We built a nice stack class that holds ints... Now we want stacks for doubles, bytes, and reference

  • bjects

We don’ t want to duplicate and maintain similar code N times

Tuesday, November 11, 14

slide-7
SLIDE 7

C++ Templates

Straightforward “macro expansion”, just plug in the type bindings Works with all types - compiler can optimize for some Writes new code for every time used - bloatware? name mangling - really messy if you see it

class Stk<T>{ T a[5]; T pop() {return a[...]} Stk<int> => {int a[5]; int pop() { return a[]} Stk<Foo> => { Foo a[5]; Foo pop() { return a[]};

Tuesday, November 11, 14

slide-8
SLIDE 8

Java Generics

Java uses C++ template syntax, but has a very different implementation - “type erasure” Evolution vs Revolution Collections arrived before Generics Didn’ t want to break old code Design was somewhat “boxed in” Very common to USE generics, primarily with Collections Framework, rare to write generic classes. Which is fortunate, because the full story of generics is quite complex

Tuesday, November 11, 14

slide-9
SLIDE 9

Generics: Type Erasure

ArrayList<Integer>, ArrayList<Long>, etc are implemented by ONE piece of code That one piece of code has NO type information - it is erased Harder to understand than templates Only works for reference objects, not primitives Leads to some peculiar problems example: Stackg

Tuesday, November 11, 14

slide-10
SLIDE 10

Java Generics

Generics eliminate casts, add type safety

List lt = new ArrayList(); lt.add(new Long(1)); Long l = (Long)lt.get(0); lt.add(new Integer(1)); / / ok

  • List lt = new ArrayList<Long>();

lt.add(new Long(1)); Long l = lt.get(0); lt.add(new Integer(1)); / / error

Tuesday, November 11, 14

slide-11
SLIDE 11

Generic Subtyping

class Super {} class Sub extends Super{} => Sub is a subtype of Super Super s = new Sub(); / / ok List<Sub> s = new ArrayList<Sub>(); List<Super> s2 = s; / / compile error s2.add(new Super()); s.get(0); List<Sub> is NOT a subtype of List<Super>

Tuesday, November 11, 14

slide-12
SLIDE 12

Generic Wildcards

void foo(Collection<Object> c) - does NOT allow all collection types, only Collection<Object> void foo(Collection<?> c) - ? is wildcard - any type, Collection<Integer>, Collection<Long> void foo(List<Super> l) - can’ t call foo with type List<Sub> Use “bounded wildcard” void foo(List<? extends Super) - now foo can be called with type List<Sub>, but not List<Object>

Tuesday, November 11, 14

slide-13
SLIDE 13

Generic Methods

The type T is “captured” from the type of the argument, then the usual replacement is performed

public static void <T> reverse( List <T> list) { List <T> tmp = new ArrayList <T>( list); for (int i = 0; i < list.size(); i + +) { list.set( i, tmp.get( list.size()-i-1)); } }

Tuesday, November 11, 14

slide-14
SLIDE 14

java.lang.Object.equals() java.lang.Object.hashCode()

hashCode() - important for hash tables, should be as “random” as possible, or hash table performance may suffer Object.hashCode() uses the memory address of the

  • bject

equals() indicates if two objects are “equal” Object.equals is the same as “==”, true only if the same object

Tuesday, November 11, 14

slide-15
SLIDE 15

Redefining equals() and hashCode()

Often useful to redefine the equals() to implement a more general concept of equality. for example, might consider two objects equal if certain fields have the same value sometimes it is useful to not compare all fields. fields not compared can be different, but objects are still “equals” if equals() is redefined, hashCode() must be redefined as well to be “consistent with equals”. if two objects are “equals”, they must have the same hashCode

Tuesday, November 11, 14

slide-16
SLIDE 16

Interface java.lang.Comparable<T>

defines a “natural ordering” implemented by many system classes like Integer, String, time and date types arrays can be sorted by “natural ordering” of elements Some collections, like TreeSet, will maintain sorted

  • rder automatically

Tuesday, November 11, 14

slide-17
SLIDE 17

java.util.Comparator<T>

Can implement the interface, instantiate an object, and pass it to various routines to supply an ordering example: compare, student

Tuesday, November 11, 14

slide-18
SLIDE 18

Collections Framework

Probably the most useful set of tools in Java Found in java.util.* (bit of a mess, lots of other stuff in there) Large package of classes for handling “collections” of reference objects Behaviors defined by interfaces Different implementations offer performance tradeoffs, with the same API java.util.Collections has many useful algorithms, like sort, binary search, reverse, min, max, etc

Tuesday, November 11, 14

slide-19
SLIDE 19

Collections Framework

Mostly superior to arrays type safety more functionality more convenient to use by default, collections print their contents. arrays do not but, use more memory than arrays for primitives

Tuesday, November 11, 14

slide-20
SLIDE 20

Collection Interface

Base interface for most collection classes(exception is Map classes) Important methods - clear, contains, add, isEmpty, size, remove, iterator, rotate, shuffle Convert to/from arrays Usually traverse with an iterator Many abstract classes make it easy to build custom implementations

Tuesday, November 11, 14

slide-21
SLIDE 21

Set Operations on Collection

addAll(c) - union removeAll(c) - difference retainAll(c) - intersection

Tuesday, November 11, 14

slide-22
SLIDE 22

Set Interface

Like Collection, but duplicates are not allowed Three implementations HashSet - most popular, fastest, unordered LinkedHashSet - maintains insertion order TreeSet - ordered by key ordering

Tuesday, November 11, 14

slide-23
SLIDE 23

List Interface

Most popular interface, ArrayList most popular implementation Generalized array - ordered collection, duplicates allowed, random access by index important methods - get, set

Tuesday, November 11, 14

slide-24
SLIDE 24

List Interface

listIterator - more powerful iterator, start at an index, can go forwards, backwards, get iterator position subList - returns a new list based on the original, but with restricted scope list.subList(3,7).clear() will remove elements at positions 3,4,5,6

Tuesday, November 11, 14

slide-25
SLIDE 25

Queue(FIFO), PriorityQueue Interfaces

Queue - LinkedList most popular implementation important methods

  • ffer() - add element to end of queue

poll() - remove element from front of queue peek() - return but do not remove front of queue PriorityQueue - elements come off in sorted order

Tuesday, November 11, 14

slide-26
SLIDE 26

Deque Interface

Double ended queue - insert and remove at each end Can be used as a stack or a queue ArrayDeque most popular implementation important methods

  • fferFirst, offerLast

removeFirst, removeLast peekFirst, peekLast

Tuesday, November 11, 14

slide-27
SLIDE 27

Map Interface

Associates keys and values HashMap most popular implementation TreeMap maintains sorted keys important methods - get, put, remove, containsKey, containsValue, keySet, values

Tuesday, November 11, 14

slide-28
SLIDE 28

“Optional” Operations

“Optional” operations are not supported by all implementations Sometimes, but not always, calling an optional

  • peration that is not supported will throw an

UnsupportedOperationException Example: Arrays.toList() does not return an ArrayList - some operations don’ t work

Tuesday, November 11, 14

slide-29
SLIDE 29

Iterating Thru Collections

Easiest way is by using implicitly using iterators in enhanced for loops Not allowed to modify a collection while iterating over it, except by using iterator methods. Collection will throw a ConcurrentModificationError example: iterate

Tuesday, November 11, 14

slide-30
SLIDE 30

Synchronized Collections

Some older “collection” classes had synchronization built in needlessly slow deprecated

Tuesday, November 11, 14

slide-31
SLIDE 31

Do Use Do NOT Use Reason java.util.ArrayList java.util.Vector synchronized, deprecated java.util.Deque java.util.Stack synchronized, deprecated java.util. HashMap, ConcurrentHashMap java.util.Hashtable synchronized, deprecated java.util.Map java.util.Dictionary deprecated

Tuesday, November 11, 14

slide-32
SLIDE 32

Assertions

Throw error if assertion is false Must be enabled on JVM command line

  • ea

Can leave them in production code

Tuesday, November 11, 14

slide-33
SLIDE 33

Generate Javadoc in Eclipse

Select the project Project/Generate Javadoc Output in console will include a path for index.html paste .../index.html into a browser

Tuesday, November 11, 14

slide-34
SLIDE 34

Java w/o Eclipse

Two basic ways to run java programs outside of Eclipse - a file hierarchy of classes, or from a jar file Can package an entire program into a “jar” file[very similar to tar file]. package/directory hierarchy is included in the jar java -jar foo.jar - run a jar file

Tuesday, November 11, 14

slide-35
SLIDE 35

Java w/o Eclipse: From File System

classpath - tells java where to find class files can be specified explicitly java -cp /rootofclasses

  • r as environment variable

export CLASSPATH=/rootofclasses the file/directory tree must mirror the package structure Given: package foo.bar; class Zap{}, class file must be CLASSPATH/foo/bar/Zap.class

Tuesday, November 11, 14

slide-36
SLIDE 36

Java w/o Eclipse: From A Jar File

“jar” is a command line tool included with java[very similar to tar] Can archive entire program class tree into a “jar” file package/directory hierarchy is included in the jar to run a jar file java -jar foo.jar to display jar contents java -tf foo.bar can also use dired in Emacs Eclipse /Export/Runnable Jar - makes a jar for proj

Tuesday, November 11, 14

slide-37
SLIDE 37

Java w/o Eclipse: From The Network

java.net.URLClassLoader

Tuesday, November 11, 14

slide-38
SLIDE 38

java.nio.*

Advanced package for doing non-blocking IO in java Very similar to using the “select” system call in linux Somewhat cumbersome package to use Difficult to get full performance Recommend using Apache “Mina” package instead

Tuesday, November 11, 14

slide-39
SLIDE 39

NIO2

java.nio.file.Path Useful functions for building and manipulating pathnames java.nio.file.Files large set of static functions for reading, writing, and manipulating files example: nio

Tuesday, November 11, 14

slide-40
SLIDE 40

Logging

Important for applications like servers java.util.logging is a builtin package apache log4j is a very popular 3rd party package

Tuesday, November 11, 14

slide-41
SLIDE 41

ProcessBuilder

Write once, run anywhere... but, sometimes you want to use other programs that run on your OS N.B. - if you don’ t read standard output, you may hang for linux people - if you want to use “*”, pipes, etc, you have to exec “bash -c ‘ls *.java|wc’ “ example: pb

Tuesday, November 11, 14