intro to java week 3
play

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


  1. Intro to Java Week 3 Tuesday, November 11, 14

  2. Homeworks 1&2 Review Hwk 1 Game, Taxi, Art, Hadamard Hwk 2 CSV , Rational/Complex, Stack Tuesday, November 11, 14

  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

  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

  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

  6. Need More Stacks! We built a nice stack class that holds ints... Now we want stacks for doubles, bytes, and reference objects We don’ t want to duplicate and maintain similar code N times Tuesday, November 11, 14

  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

  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

  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

  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

  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

  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

  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

  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 object equals() indicates if two objects are “equal” Object.equals is the same as “==”, true only if the same object Tuesday, November 11, 14

  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

  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 order automatically Tuesday, November 11, 14

  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

  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

  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

  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

  21. Set Operations on Collection addAll(c) - union removeAll(c) - difference retainAll(c) - intersection Tuesday, November 11, 14

  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

  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

  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

  25. Queue(FIFO), PriorityQueue Interfaces Queue - LinkedList most popular implementation important methods offer() - 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

  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 offerFirst, offerLast removeFirst, removeLast peekFirst, peekLast Tuesday, November 11, 14

  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

  28. “Optional” Operations “Optional” operations are not supported by all implementations Sometimes, but not always, calling an optional operation 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

  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

  30. Synchronized Collections Some older “collection” classes had synchronization built in needlessly slow deprecated Tuesday, November 11, 14

  31. Do Use Do NOT Use Reason synchronized, java.util.ArrayList java.util.Vector deprecated synchronized, java.util.Deque java.util.Stack deprecated java.util. synchronized, HashMap, java.util.Hashtable deprecated ConcurrentHashMap java.util.Map java.util.Dictionary deprecated Tuesday, November 11, 14

Recommend


More recommend