Java 1.5 26-Jul-16

advertisement
Java 1.5
26-Jul-16
Java 1.5.0 beta 1 (“Tiger”)



Released February 4, 2004
http://java.sun.com/j2se/1.5/index.jsp
Themes






Ease of Development
Scalability and Performance
Monitoring and Manageability
Desktop Client
Miscellaneous Features
To use Java 1.5:




Download and install from http://java.sun.com/j2se/1.5.0/index.jsp
Use the -source 1.5 flag
Optionally, get: NetBeans 3.6, or...
...get Eclipse 3.0 build M8 and the JDK 15. plugin
http://eclipse-plugins.2y.net/eclipse/plugin_details.jsp?id=497
2
Generic types


Up through Java 1.4, collections hold arbitrary Objects
If you wanted, say, a Vector of Employees, you had two basic
choices:

Use a Vector



Extend Vector with an EmployeeVector class



Adding an Employee is easy (but so is adding any other Object, however
inappropriate)
Getting an Employee from the Vector usually requires a cast, which may
result in a runtime error
Checking is done at compile time (which is better than runtime)
It’s a lot of extra work
Generic types do the second of these automatically for you

Syntax:
Vector<Employee> employees = new Vector<Employee>();
3
An example

Instead of:


You can say:


ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
Advantages:




ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();
Less work to create specialized data structures
Checking done at compile time rather than runtime
For C++ programmers, the syntax is familiar
Disadvantage:

Yet more ugly syntax to learn
4
More generics


A lot of other things, besides collections, have been “genericized”
in Java 1.5
Parameterized Type



Interface


interface List<Element> implements MyInterface{...}
Class



Vector<String> stringVector = new Vector<String>
List<Integer> integerList = new List<Integer>
class MyList<Element> {...}
class MyList<Element> implements List<Element> {...}
Method


boolean containsBoth(Element a, Element b);
static <Element> boolean swap(List<Element> list, int i, int j);
5
Autoboxing

Up through Java 1.4, primitive types cannot be used
where an object is required



Primitive types still cannot be used where an object is
required…
…But Java 1.5 now does this conversion automatically:


They had to be wrapped, or boxed, for instance:
myStack.push(new Integer(25));
Now you can say myStack.push(25);
What happens at runtime is still the same

It’s just that the compiler does the conversion for you
6
Auto-unboxing

Just as you could not use primitive types where an Object was
required, you could not use an Object where a primitive type was
required




You had to do your own unwrapping, or un-boxing
For instance, you had to write code such as:
int result = ((Integer)myStack.pop()).intValue();
Now you can just write:
int result = myStack.pop();
Even more striking,
myStack.push(new Integer(((Integer)myStack.pop()).intValue() +
((Integer)myStack.pop()).intValue()));
becomes
myStack.push(myStack.pop() + myStack.pop());
7
Combining generics with autoboxing

Instead of:


You can say:


ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
Advantages:


Less code to write
Code becomes more readable
8
Auto [un]boxing disadvantages


Since more is hidden, it becomes harder to understand
and explain what is going on
Equality is no longer transitive! Consider:




Integer a = new Integer(7);
int b = 7;
Integer c = new Integer(7);
if (a == b) … // will be true
if (b == c) … // will be true
if (a == c) … // will be false
For Objects, == is an identity test
This is a dangerous trap for the unwary
9
New for loop



Many collections in Java use Iterators
The new for loop automatically uses an Iterator
Example Java 1.4 code:


Example Java 1.5 code:


for (Employee employee : employeeList) {
System.out.println(employee.getName());
}
Advantage:



for (Iterator iter = employeeList.iterator(); iter.hasNext(); ) {
Employee employee =(Employee)iter.next();
System.out.println(employee.getName());
}
Convenient and fairly easy to read
Also works for iterators you define
Disadvantage: Stupid syntax (I wish they had used “in”)
10
Enumerated types

Enumerated types are a way of representing nonstandard data,
such as days of the week, with integers:


Or months of the year:


static final int JANUARY = 0;
static final int FEBRUARY = 1;
…
The problem with this approach is that there are so many ways to
make errors:



static final int SUNDAY = 1;
static final int MONDAY = 2;
…
static final int DECEMBER = 12;
int date = year + month + dayOfWeek;
Over the past few years there have been many attempts to define
an idiom for making type-safe enumerations
11
Enumerated types in Java 1.5

public enum Suit {clubs, diamonds, hearts, spades}
 Notice new keyword “enum”
 Values of enum constants are assigned automatically
public enum Coin{
penny(1), nickel(5), dime(10), quarter(25); // values
Coin(int value) { this.value = value; }
// constructor
private final int value;
// instance variable
public int value() { return value; }
// method
}



This is very like a class declaration
Printing results in the named constant: dime, not 10
Named constants can be read in
12
Using an enumerated type

public class CoinTest {
public static void main(String[] args) {
for (Coin c : Coin.VALUES)
System.out.println(c + ": \t" + c.value() +"¢ \t" + color(c));
}
private enum CoinColor { copper, nickel, silver }
}
private static CoinColor color(Coin c) {
switch(c) {
case Coin.penny: return CoinColor.copper;
case Coin.nickel: return CoinColor.nickel;
case Coin.dime: // deliberate fall through to next case
case Coin.quarter: return CoinColor.silver;
default: throw new AssertionError("Unknown coin: " + c);
}
}
13
Advantages of enumerated types





enum types simplify code and make it more readable
Types are checked at compile time (hence, very type safe)
Performance is comparable to int constants
Each enum type has its own name space (you don't have to say Coin.dime)
You can add, reorder or even remove constants without the need to recompile
other classes that use these constants







I’ve seen one source that says you do need to recompile
Printed values are informative
enum constants can be used in collections (for example, as HashMap keys)
You can add arbitrary fields and methods to an enum class
An enum type can be made to implement arbitrary interfaces
enum types can be used in switch statements
enum types are serializable
14
Disadvantages of enumerated types

Still more complexity in the language

Harder for beginners, nicer for experts!
15
The “Constant Interface” antipattern

public interface Physics {
public static final double AVOGADROS_NUMBER = 6.02214199e23;
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
public static final double ELECTRON_MASS
= 9.10938188e-31;
}
public class Guacamole implements Physics {
public static void main(String[] args) {
double moles = ...;
double molecules = AVOGADROS_NUMBER * moles;
...
}
}

This is considered to be very poor style by smart programmers
who have thought about it a lot more than I have
16
Static import



You can now import just the static members of a class or interface
public interface Physics { // as before
public static final double AVOGADROS_NUMBER = 6.02214199e23;
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
public static final double ELECTRON_MASS
= 9.10938188e-31;
}
import static org.iso.Physics.*;
class Guacamole {
public static void main(String[] args) {
double molecules = AVOGADROS_NUMBER * moles;
...
}
}
17
Metadata

Metadata lets you avoid writing boilerplate code, by
enabling tools to generate it from annotations in the
source code



This leads to a “declarative” programming style where the
programmer says what should be done, and tools emit the
code to do it
Details are tool-dependent, but the syntax involves the use of
the @ sign
I have not yet seen any good, understandable examples
18
Varargs

If you want to pass a variable number of arguments to a method,
you currently have to put them into an array



This is a lot of extra, messy code
Java 1.5 allows varargs—a variable number of arguments
Example:
public String format(String pattern, Object... args) {...}



The ellipsis (...) after Object is the new syntax
The varargs must be the very last thing in the parameter list
Within the method, args has type Object[ ]


No extra syntax is needed within the method—args is just an array
No new syntax is needed to call—just supply the parameters you want
19
Improved output

The new Formatter class, modeled after C’s printf
statement, gives you much simpler formatted output

This class provides support for:





Layout justification and alignment
Common formats for numeric, string, and date/time data
Locale-specific output
Common Java types such as byte, BigDecimal, and Calendar
Limited formatting customization for arbitrary user types is
provided through the Formattable interface
20
Improved input

The new Scanner class can parse primitive types and
strings using regular expressions


The Scanner class can also read in input from a String (not
just an I/O stream)
Thankfully, this class was not modeled after C’s scanf!
21
Other stuff






Lots of new classes and interfaces, such as Queue and
PriorityQueue, MouseInfo
More “looks and feels:” Synth and Ocean
Enhancements to sound and image processing
Improvements in tools (javac, javadoc, JVMTI, JPDA)
Other improvements in networking, security,
internationalization, etc.
Bug fixes (of course)
22
Final comments



As I said at the beginning of CIT591, the half-life of
knowledge in computer science is about 5 years
You are well-prepared to learn Java 1.5, since it’s
mostly “more of the same”
I expect to convert to Java 1.5 as soon as classes are
over, and use it in the Fall
23
The End
“Well, in our country,” said Alice, panting a little, “You’d
generally get somewhere else if you ran very fast for a long
time, as we’ve been doing.”
“A slow sort of country!” said the Queen. “Now here, you
see, it takes all the running you can do to keep in the same
place. If you want to get somewhere else, you must run at
least twice as fast as that!”
—Lewis Carroll, Alice in Wonderland
24
Download