Your SlideShare is downloading. ×
Introduction to Intermediate Java
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Introduction to Intermediate Java

1,204
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,204
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
15
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

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