in collections - ics-software
Download
Report
Transcript in collections - ics-software
Intermediate Java, Part 1
Philip Johnson
Collaborative Software Development Laboratory
Information and Computer Sciences
University of Hawaii
Honolulu HI 96822
(1)
Goals of this talk
Assumptions:
• You are comfortable with the basis syntax and
control structures of Java.
(2)
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
Best resources for this material
Java in a Nutshell
•5th Edition
Effective Java
•2nd Edition
(3)
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
(4)
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();
(5)
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.
(6)
Additional Collections
HashSet
LinkedHashSet
EnumSet
TreeSet
CopyOnWriteArraySet
ArrayList
LinkedList
CopyOnWriteArrayList
(7)
HashMap
ConcurrentHashMap
EnumMap
LinkedHashMap
TreeMap
IdentityHashMap
WeakHashMap
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
(8)
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?
(9)
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?
(10)
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.
(11)
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).
(12)
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");
}
(13)
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? If anything?
(14)
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!
(15)
Problem: Readability
The code is hard to read and ugly.
(16)
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.
(17)
Generic Types
With Java 5, you can rewrite concat like this:
public String concat(List<String> list) {
StringBuffer buff = new StringBuffer();
for (element : list) {
buff.append(element);
}
return buff.toString();
}
This is shorter, clearer, and guarantees that
element is of type String.
(18)
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" typeconsistency of your system.
(19)
Inside world vs. Outside World
Outside World
(Databases, command line, web forms)
Must check input types!
Your System
(Internally Type Safe)
(20)
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?
(21)
NumStack class skeleton
public class NumStack<N extends Number> {
private Stack<N>;
public void add(N number) ...
}
(22)
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;
}
(23)
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!
(24)
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.
(25)
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.
(26)
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 CodeRuler
assignment.
(27)