Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.
-
date post
21-Dec-2015 -
Category
Documents
-
view
220 -
download
1
Transcript of Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.
Compilation 2007Compilation 2007
Java 1.5 FeaturesJava 1.5 Features
Michael I. Schwartzbach
BRICS, University of Aarhus
2Java 1.5 Features
Java 1.5 Features (That We Will Use)Java 1.5 Features (That We Will Use)
enums autoboxing improved for loop generic collections generic classes @override annotations covariant return types
3Java 1.5 Features
Constant Values as Static Fields (1/2)Constant Values as Static Fields (1/2)
public class Test {
public static final int TrafficSignal_RED = 0;
public static final int TrafficSignal_YELLOW = 1;
public static final int TrafficSignal_GREEN = 2;
public static int duration(int color) {
switch (color) {
case TrafficSignal_RED: return 35;
case TrafficSignal_YELLOW: return 15;
case TrafficSignal_GREEN: return 40;
}
return 0;
}
public static String name(int color) {
switch (color) {
case TrafficSignal_RED: return "RED";
case TrafficSignal_YELLOW: return "YELLOW";
case TrafficSignal_GREEN: return "GREEN";
}
return "";
}
4Java 1.5 Features
Constant Values as Static Fields (2/2)Constant Values as Static Fields (2/2)
public static void main(String[] args) throws Exception {
int[] states = { TrafficSignal_RED, TrafficSignal_YELLOW,
TrafficSignal_GREEN, TrafficSignal_YELLOW };
int i = 0;
while (true) {
System.out.println(name(states[i]));
Thread.sleep(1000*duration(states[i]));
i = (i+1)%states.length;
}
}
}
• Not typesafe
• No proper namespace
• Constants compiled into clients
• Annoying to use
5Java 1.5 Features
Type-Safe EnumsType-Safe Enums
public class Test {
public enum TrafficSignal { RED, YELLOW, GREEN };
public static int duration(TrafficSignal color) {
switch (color) {
case RED: return 35;
case YELLOW: return 15;
case GREEN: return 40;
}
return 0;
}
public static void main(String[] args) throws Exception {
TrafficSignal[] states = { TrafficSignal.RED, TrafficSignal.YELLOW,
TrafficSignal.GREEN, TrafficSignal.YELLOW };
int i = 0;
while (true) {
System.out.println(states[i]);
Thread.sleep(1000*duration(states[i]));
i = (i+1)%states.length;
}
}
}
6Java 1.5 Features
Constructors, Fields, and MethodsConstructors, Fields, and Methods
public class Test {
public enum TrafficSignal {
RED(35), YELLOW(15), GREEN(40);
protected int duration;
TrafficSignal(int duration) { this.duration = duration; }
int getDuration() { return duration; }
};
public static void main(String[] args) throws Exception {
TrafficSignal[] states = { TrafficSignal.RED,
TrafficSignal.YELLOW,
TrafficSignal.GREEN,
TrafficSignal.YELLOW };
int i = 0;
while (true) {
System.out.println(states[i]);
Thread.sleep(1000*states[i].getDuration());
i = (i+1)%states.length;
}
}
}
7Java 1.5 Features
int i1 = 42;
Integer i2;
i2 = new Integer(i1);
i1 = i2.intValue();
Map m = new HashMap();
m.put(new Integer(87), new Integer(i1));
i2 = (Integer)m.get(new Integer(87));
Annoying ConversionsAnnoying Conversions
8Java 1.5 Features
int i1 = 42;
Integer i2;
i2 = new Integer(i1);
i1 = i2.intValue();
Map m = new HashMap();
m.put(new Integer(87), new Integer(i1));
i2 = (Integer)m.get(new Integer(87)); int i1 = 42;
int i1 = 42;
Integer i2;
i2 = i1;
i1 = i2;
Map m = new HashMap();
m.put(87, i1);
i2 = (Integer)m.get(87);
Automatic Boxing and UnboxingAutomatic Boxing and Unboxing
9Java 1.5 Features
Getting Rid of the Last CastGetting Rid of the Last Cast
int i1 = 42;
Integer i2;
i2 = i1;
i1 = i2;
Map m = new HashMap();
m.put(87, i1);
i2 = (Integer)m.get(87);
int i1 = 42;
Integer i2;
i2 = i1;
i1 = i2;
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
m.put(87, i1);
i2 = m.get(87);
10Java 1.5 Features
Generic CollectionsGeneric Collections
Type parameters Type checker inserts the required casts The type checker ensures casts will never fail The type checker warns if it is not sure No runtime improvement, casts still take place
(unless JVM optimizes) Required to be backward compatible
11Java 1.5 Features
Generic Collections in ActionGeneric Collections in Action
Student johnni = new Student(”Johnni");
List<Student> phds = new ArrayList<Student>();
phds.add(johnni);
Student phd = phds.get(0); // no cast needed
phds.add(”Janus"); // cool type error
for (Iterator<Student> i = phds.iterator();
i.hasNext(); ) {
Student p = i.next(); // no cast needed
System.out.println(p.name());
if (p.papers() < 3) i.remove();
}
12Java 1.5 Features
No Type Information at RuntimeNo Type Information at Runtime
List<Student> phds = new ArrayList<Student>();
phds instanceof List // true
phds instanceof List<Student> // syntax error
13Java 1.5 Features
Mixing Raw and Generic CollectionsMixing Raw and Generic Collections
Student johnni = new Student(“Johnni");
List phds = new ArrayList();
phds.add(johnni);
phds.add(“Janus"); // no type error
for (Iterator<Student> i = phds.iterator(); i.hasNext(); ) {
Student p = i.next(); // no cast needed
System.out.println(p.name());
if (p.papers() < 3) i.remove();
}
Compiles, but fails at runtime. But the compiler warns you:
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
14Java 1.5 Features
Nesting Parameterized TypesNesting Parameterized Types
Map<Advisor, List<Student>> phdSchool;
Map<String,Map<Advisor, List<Student>>> phdSchools;
Advisor michael;
...
System.out.println(
phdSchools.get("BRICS").get(michael).get(0).name()
);
15Java 1.5 Features
Invariant Subtyping of ParametersInvariant Subtyping of Parameters
class Student extends Person { ... }
...
List<Person> people = new ArrayList<Person>();
// perfectly fine since ArrayList is a subtype of List
List<Student> phds = new ArrayList<Student>();
// perfectly fine since ArrayList is a subtype of List
people = phds; // type error
16Java 1.5 Features
And for a Good ReasonAnd for a Good Reason
class Student extends Person { ... }
class Advisor extends Person { ... }
...
List<Person> people = new ArrayList<Person>();
List<Student> phds new ArrayList<Student>();
people = phds; // assume this is allowed
people.add(new Advisor("Michael"));
phds.get(0).studentid();
// runtime error, an Advisor doesn't have a studentid
17Java 1.5 Features
Same Problem with ArraysSame Problem with Arrays
class Student extends Person { ... }
class Advisor extends Person { ... }
...
Student[] phds = new Student[100];
Person[] people = new Person[100];
people = phds; // allowed, but unsound
people[0] = new Advisor();
phds[0].studentid(); // runtime error
Pragmatic (but later regretted) design choice
18Java 1.5 Features
Print All Elements of Any ListPrint All Elements of Any List
public void printList(List x) throws IOException {
for (Iterator i = x.iterator(); i.hasNext(); ) {
System.out.println(i.next().toString());
}
}
List<Student> phds;
List<Person> people;
printList(phds); // unchecked warning
printList(people); // unchecked warning
19Java 1.5 Features
Another Attempt with GenericsAnother Attempt with Generics
public void printList(List<Object> x)
throws IOException {
for (Iterator<Object> i = x.iterator();
i.hasNext(); ) {
System.out.println(i.next().toString());
}
}
List<Student> phds;
List<Person> people;
printList(phds); // type error
printList(people); // type error
20Java 1.5 Features
Wildcards to The RescueWildcards to The Rescue
public void printList(List<?> x) throws IOException {
for (Iterator<?> i = x.iterator(); i.hasNext(); ) {
System.out.println(i.next().toString());
}
}
List<Student> phds;
List<Person> people;
printList(phds); // allowed
printList(people); // allowed
21Java 1.5 Features
Write Your Own Generic ClassWrite Your Own Generic Class
public class Queue<T> {
protected List<T> s;
public Queue() {
s = new ArrayList<T>();
}
public void enter(T x) {
s.add(x);
}
public T leave() {
if (s.size()==0) return null;
else return s.remove(0);
}
}
22Java 1.5 Features
Bounded Type ParametersBounded Type Parameters
class PersonQueue<T extends Person> {
protected List<T> s;
public PersonQueue() {
s = new ArrayList<T>();
}
public void enter(T x) {
s.add(x);
}
public T leave() {
if (s.size()==0) return null;
else return s.remove(0);
}
public String first() {
if (s.size()==0) return null;
return s.get(0).name();
}
}
23Java 1.5 Features
Using InheritanceUsing Inheritance
class PersonQueue<T extends Person> extends Queue<T> {
public String first() {
return s.get(0).name();
}
}
24Java 1.5 Features
For Loop for Collection ClassesFor Loop for Collection Classes
for (Iterator<Person> i = phds.iterator(); i.hasNext(); ) {
Person p = i.next();
System.out.println(p.name());
}
for (Person p: phds) {
System.out.println(p.name());
}
But we cannot remove, need old iterators for that
25Java 1.5 Features
Person phds[] = { new Person(”Johnni"),
new Person(”Janus") };
for (Person p: phds) {
System.out.println(p.name());
}
Works for Arrays as WellWorks for Arrays as Well
26Java 1.5 Features
Override ProblemOverride Problem
public class Graduate extends Person {
public String naem() {
return super.name()+", PhD";
}
}
Nothing happens, the PhD disappeared
27Java 1.5 Features
The The @Override@Override Annotation Annotation
public class Graduate extends Person {
public @Override String naem() {
return super.name()+", PhD";
}
}
Compiler error:
method does not override a method from its superclass
28Java 1.5 Features
Return Type ProblemReturn Type Problem
public class Person {
protected String name;
public Person(String name) {
this.name = name;
}
public Person changeName(String newName) {
this.name = newName;
return this;
}
}
...
public Student extends Person { ... }
...
Student x;
...
x.changeName(”Johnny").papers() // type error