Introduction to Intermediate Java

1,406 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,406
On SlideShare
0
From Embeds
0
Number of Embeds
67
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Introduction to Intermediate Java

  1. 1. Intermediate Java Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu HI 96822
  2. 2. Goals of this talk <ul><li>Assumptions: </li></ul><ul><ul><li>You are comfortable with the basis syntax and control structures of Java. </li></ul></ul><ul><li>Become familiar with “modern” (post Java 5) constructs: </li></ul><ul><ul><li>Collection classes </li></ul></ul><ul><ul><ul><li>General features </li></ul></ul></ul><ul><ul><ul><li>Generics and parameterization </li></ul></ul></ul><ul><ul><ul><li>Overriding equals() and hashCode() </li></ul></ul></ul><ul><ul><li>Enumerations </li></ul></ul><ul><ul><li>Defining generic abstract types </li></ul></ul><ul><ul><li>For-each control structure </li></ul></ul><ul><ul><li>Autoboxing </li></ul></ul><ul><ul><li>Annotations </li></ul></ul>
  3. 3. Best resources for this material <ul><li>Java in a Nutshell </li></ul><ul><ul><li>5th Edition </li></ul></ul><ul><li>Effective Java </li></ul><ul><ul><li>2nd Edition </li></ul></ul>
  4. 4. Collections <ul><li>Java provides a &quot;Collections Framework&quot; with the following top-level abstract class: </li></ul><ul><li>Collection<E>: </li></ul><ul><ul><li>group of Objects of type E </li></ul></ul><ul><ul><li>may or may contain duplicates </li></ul></ul><ul><ul><li>may or may not impose an ordering </li></ul></ul><ul><ul><li>Operations: add, remove, contains, iterate </li></ul></ul>
  5. 5. Example Collection code <ul><li>Collection<String> strings = new HashSet<String>(); </li></ul><ul><li>Collection<String> nums = Arrays.asList(&quot;one&quot;, &quot;two&quot;); </li></ul><ul><li>strings.addAll(nums); </li></ul><ul><li>strings.add(&quot;three&quot;); </li></ul><ul><li>strings.remove(&quot;zero&quot;); </li></ul><ul><li>boolean noStrings = strings.isEmpty(); </li></ul>
  6. 6. Basic Collection views/subinterfaces <ul><li>Set: </li></ul><ul><ul><li>A collection that does not allow duplicates. </li></ul></ul><ul><ul><li>No new operations; add works differently </li></ul></ul><ul><li>SortedSet: </li></ul><ul><ul><li>traverses elements in their &quot;natural order&quot;. </li></ul></ul><ul><ul><li>Additional operations: first(), last(), etc. </li></ul></ul><ul><li>List: </li></ul><ul><ul><li>Ordered collection, duplicates allowed. </li></ul></ul><ul><ul><li>Like an array with flexible size </li></ul></ul><ul><li>Map: </li></ul><ul><ul><li>A set of keys, each mapped to a value. </li></ul></ul><ul><ul><li>Not a collection, but keys and values can be viewed as collections. </li></ul></ul>
  7. 7. Additional Collections <ul><li>HashSet </li></ul><ul><li>LinkedHashSet </li></ul><ul><li>EnumSet </li></ul><ul><li>TreeSet </li></ul><ul><li>CopyOnWriteArraySet </li></ul><ul><li>ArrayList </li></ul><ul><li>LinkedList </li></ul><ul><li>CopyOnWriteArrayList </li></ul><ul><li>HashMap </li></ul><ul><li>ConcurrentHashMap </li></ul><ul><li>EnumMap </li></ul><ul><li>LinkedHashMap </li></ul><ul><li>TreeMap </li></ul><ul><li>IdentityHashMap </li></ul><ul><li>WeakHashMap </li></ul>
  8. 8. Prohibited Classes for 413/613 <ul><li>The following classes are hold-overs from Java 1.0 and should not be used: </li></ul><ul><li>Vector() </li></ul><ul><ul><li>Use ArrayList() instead </li></ul></ul><ul><li>Hashtable </li></ul><ul><ul><li>Use HashMap() instead </li></ul></ul>
  9. 9. Collections and Design <ul><li>The choice of a collection tells the reader what you intend to do with it. </li></ul><ul><li>Example: Assume you need to keep a list of strings in alphabetic order without any duplicates. What collection class would you choose? </li></ul>
  10. 10. Proper design of collection elements <ul><li>Assume you want to: </li></ul><ul><ul><li>design a class called CompactDisc </li></ul></ul><ul><ul><li>hold instances in a collection </li></ul></ul><ul><ul><li>retrieve instances by their title </li></ul></ul><ul><ul><li>produce a sorted list by title </li></ul></ul><ul><li>What collection class might you use? </li></ul><ul><li>What methods of Object() should be overridden in CompactDisc? </li></ul>
  11. 11. Collection class element design <ul><li>Almost all classes that you design that might be placed into collections should override equals() and hashCode() (and perhaps compareTo()). </li></ul><ul><ul><li>Override equals() to use “logical” equality, not “instance” equality </li></ul></ul><ul><ul><li>Override hashCode() so that equivalent objects have the same hashCode() value. </li></ul></ul><ul><ul><li>Override compareTo() (and implement Comparable) when using your class in sorted collections. </li></ul></ul><ul><li>See Readings for details on how to properly override these methods. </li></ul>
  12. 12. Enumerated Types <ul><li>Defines a finite set of values that can be checked at compile time. </li></ul><ul><li>public enum Colors {BLUE, RED, GREEN} </li></ul><ul><li>Formatting conventions: </li></ul><ul><ul><li>An enumerated type is capitalized like a class (first letter of each word upper case). </li></ul></ul><ul><ul><li>The elements are capitalized like constants (all letters upper case). </li></ul></ul>
  13. 13. Enum Examples <ul><li>public enum Colors {BLUE, RED, GREEN}; </li></ul><ul><li>public void foo(Colors color) { </li></ul><ul><li>if (color == BLUE) { </li></ul><ul><li>System.out.println(&quot;Sky&quot;); </li></ul><ul><li>} </li></ul><ul><li>if (color.toString().equals(&quot;Red&quot;)) { </li></ul><ul><li>System.out.println(&quot;Wine&quot;); </li></ul><ul><li>} </li></ul><ul><li>if (Colors.valueOf(&quot;GREEN&quot;) == GREEN) { </li></ul><ul><li>System.out.println(&quot;of course it's green&quot;); </li></ul><ul><li>} </li></ul>
  14. 14. Generic Types <ul><li>Prior to Java 5, people wrote code like this: </li></ul><ul><li>public String concat(List list) { </li></ul><ul><li>StringBuffer buff = new StringBuffer(); </li></ul><ul><li>for (Iterator i = list.iterator(); i.hasNext();) { </li></ul><ul><li>String element = (String) i.next(); </li></ul><ul><li>buff.append(element); </li></ul><ul><li>} return buff.toString(); </li></ul><ul><li>} </li></ul><ul><li>What's wrong with this picture? </li></ul>
  15. 15. Problem: Type Safety <ul><li>concat is implemented correctly, but assumes that it will always be passed a list of Strings. </li></ul><ul><li>Passing concat a &quot;corrupted&quot; List (such as one that contains an Integer) show up at run-time as a ClassCastException. </li></ul><ul><li>This may happen regularly, or rarely, or only if the program encounters an &quot;unexpected&quot; condition. </li></ul><ul><li>This is a significant source of unreliability! </li></ul>
  16. 16. Problem: Readability <ul><li>The code is hard to read and ugly. </li></ul>
  17. 17. The advantage of generics <ul><li>1. You can declare the type of the elements in a data structure and find errors at compile-time, not after the system is running. </li></ul><ul><li>2. The type declarations form a kind of &quot;executable documentation&quot; that helps maintainers use the system and its API correctly. </li></ul><ul><li>3. The system is guaranteed to be &quot;internally&quot; type consistent. </li></ul>
  18. 18. Generic Types <ul><li>With Java 5, you can rewrite concat like this: </li></ul><ul><li>public String concat(List<String> list) { </li></ul><ul><li>StringBuffer buff = new StringBuffer(); </li></ul><ul><li>for (String element : list) { </li></ul><ul><li>buff.append(element); </li></ul><ul><li>} return buff.toString(); </li></ul><ul><li>} </li></ul><ul><li>This is shorter, clearer, and guarantees that element is of type String. </li></ul>
  19. 19. Limitations of Generics <ul><li>1. 'null' is an acceptable instance of all types, so List<String> does not prevent an element from being 'null'. </li></ul><ul><li>2. Type-level errors can still occur when the system interacts with the outside world. </li></ul><ul><ul><li>Generics only guarantee &quot;internal&quot; type-consistency of your system. </li></ul></ul>
  20. 20. Inside world vs. Outside World Your System (Internally Type Safe) Outside World (Databases, command line, web forms) Must check input types!
  21. 21. Creating generic classes <ul><li>Generic classes reduce errors when using the Java API, such as collection classes. </li></ul><ul><li>Generic classes also allow you to design systems that are easier to use without error. </li></ul><ul><li>Consider a class that contains a Stack of Numbers. How might that be defined with generics? </li></ul>
  22. 22. NumStack class skeleton <ul><li>public class NumStack<N extends Number> { </li></ul><ul><li>private Stack<N>; </li></ul><ul><li>public void add(N number) ... </li></ul><ul><li>} </li></ul>
  23. 23. Autoboxing <ul><li>Prior to Java 5, manipulating &quot;primitive&quot; types (int, float, double, etc.) in collections (HashMap, ArrayList, etc.) was a hassle: </li></ul><ul><li>public int add(List list) { </li></ul><ul><li>int total = 0; </li></ul><ul><li>for (Iterator i = list.iterator(); i.hasNext();) { </li></ul><ul><li>Integer element = (Integer) i.next(); </li></ul><ul><li>total += element.intValue(); </li></ul><ul><li>} return total; </li></ul><ul><li>} </li></ul>
  24. 24. Autoboxing <ul><li>Java 5 moves the conversion between Integer and int, Float and float, etc. into the compiler, so you can write: </li></ul><ul><li>public int add(List<Integer> list) { </li></ul><ul><li>int total = 0; </li></ul><ul><li>for (int num : list) { </li></ul><ul><li>total += num; </li></ul><ul><li>} return total; </li></ul><ul><li>} </li></ul><ul><li>Note how this example uses generics, for-each, and autoboxing! </li></ul>
  25. 25. Annotations <ul><li>Provide the ability to associate “metadata” with program elements. </li></ul><ul><li>Annotations cannot change the way the program runs! </li></ul><ul><ul><li>The java interpreter ignores annotations. </li></ul></ul><ul><li>Annotations enable Java tools (compiler, javadoc, checkstyle, PMD, etc.) to find errors in your code more effectively. </li></ul>
  26. 26. Useful Annotations <ul><li>@Override </li></ul><ul><ul><li>Used by the Java compiler to issue a warning when a method does not actually override a superclass method. </li></ul></ul><ul><li>@Test </li></ul><ul><ul><li>Used by the JUnit tool to determine which methods are JUnit test cases. </li></ul></ul><ul><li>@GuardedBy </li></ul><ul><ul><li>Used by the PMD tool to indicate that a field must be accessed when holding a lock. </li></ul></ul>
  27. 27. Where to go from here <ul><li>Read Java in a Nutshell and Effective Java. </li></ul><ul><li>Be careful when reading “old” Java code: there are billions of lines of legacy Java that do not use modern constructs! </li></ul><ul><li>Use modern constructs in your code. </li></ul><ul><li>Most RoboCode sample Robots do not use modern constructs! You must update such code if you adapt it for your robots! </li></ul>

×