Introduction to Intermediate Java

28
1) Intermediate Java Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu HI 96822

description

 

Transcript of Introduction to Intermediate Java

Page 1: Introduction to Intermediate Java

(1)

Intermediate Java

Philip Johnson

Collaborative Software Development Laboratory

Information and Computer Sciences

University of Hawaii

Honolulu HI 96822

Page 2: Introduction to Intermediate Java

(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

Page 3: Introduction to Intermediate Java

(3)

Best resources for this material Java in a Nutshell•5th Edition

Effective Java•2nd Edition

Page 4: Introduction to Intermediate Java

(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

Page 5: Introduction to Intermediate Java

(5)

Example Collection code

Collection<String> strings = new HashSet<String>(); Collection<String> nums = Arrays.asList("one", "two");

strings.addAll(nums); strings.add("three");

strings.remove("zero");

boolean noStrings = strings.isEmpty();

Page 6: Introduction to Intermediate Java

(6)

Basic Collection views/subinterfaces Set:•A collection that does not allow duplicates.•No new operations; add works differently

SortedSet:•traverses elements in their "natural order".•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.

Page 7: Introduction to Intermediate Java

(7)

Additional Collections HashSet

LinkedHashSet

EnumSet

TreeSet

CopyOnWriteArraySet

ArrayList

LinkedList

CopyOnWriteArrayList

HashMap

ConcurrentHashMap

EnumMap

LinkedHashMap

TreeMap

IdentityHashMap

WeakHashMap

Page 8: Introduction to Intermediate Java

(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

Page 9: Introduction to Intermediate Java

(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?

Page 10: Introduction to Intermediate Java

(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?

Page 11: Introduction to Intermediate Java

(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.

Page 12: Introduction to Intermediate Java

(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).

Page 13: Introduction to Intermediate Java

(13)

Enum Examples public enum Colors {BLUE, RED, GREEN};

public void foo(Colors color) { if (color == BLUE) { System.out.println("Sky"); }

if (color.toString().equals("Red")) { System.out.println("Wine"); }

if (Colors.valueOf("GREEN") == GREEN) { System.out.println("of course it's green"); }

Page 14: Introduction to Intermediate Java

(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?

Page 15: Introduction to Intermediate Java

(15)

Problem: Type Safety concat is implemented correctly, but assumes that it will always be passed a list of Strings.

Passing concat a "corrupted" 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 "unexpected" condition.

This is a significant source of unreliability!

Page 16: Introduction to Intermediate Java

(16)

Problem: Readability The code is hard to read and ugly.

Page 17: Introduction to Intermediate Java

(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 "executable documentation" that helps maintainers use the system and its API correctly.

3. The system is guaranteed to be "internally" type consistent.

Page 18: Introduction to Intermediate Java

(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.

Page 19: Introduction to Intermediate Java

(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 "internal" type-consistency of your system.

Page 20: Introduction to Intermediate Java

(20)

Inside world vs. Outside World

Your System(Internally Type Safe)

Outside World(Databases, command line, web forms)

Must check input types!

Page 21: Introduction to Intermediate Java

(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?

Page 22: Introduction to Intermediate Java

(22)

NumStack class skeleton public class NumStack<N extends Number> {

private Stack<N>;

public void add(N number) ...

}

Page 23: Introduction to Intermediate Java

(23)

Autoboxing

Prior to Java 5, manipulating "primitive" 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; }

Page 24: Introduction to Intermediate Java

(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!

Page 25: Introduction to Intermediate Java

(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.

Page 26: Introduction to Intermediate Java

(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.

Page 27: Introduction to Intermediate Java

(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!

Page 28: Introduction to Intermediate Java

(28)