220 likes | 360 Views
Java 5 Part 2. CSE301 University of Sunderland Harry Erwin, PhD. Introduction. Java 5 has been changed to improve the language. This lecture will discuss the changes. You will be tested on your knowledge of Java 5. References include:
E N D
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD
Introduction • Java 5 has been changed to improve the language. • This lecture will discuss the changes. You will be tested on your knowledge of Java 5. • References include: • McLaughlin and Flanagan, 2004, Java 1.5 Tiger: A Developer’s Notebook, O’Reilly • Flanagan, 2005, Java in a Nutshell, 5th edition, O’Reilly
Part 1 (Last Lecture) Arrays Queues Overriding return types Unicode StringBuilder Generics Part 2 (Today) Enumerated types Boxing Annotations for/in Static imports Formatting Threading Topics
Enumerated types • If you’ve worked with C++, you already know how enums can be used as integer types to avoid the need for ‘magic numbers’. • In Java 1.4 and earlier, there were two ways to define new types: classes and interfaces. This did not cover some very specific programming needs. • One such need was for a type that could have a very limited number of values. The new enumerated type or enum serves this need. (An enum is just a Java class.) • Many potential questions throughout.
enum Syntax • enum enumName {list of values}; • The value list names are all uppercase by convention. Comma-separated. See next slide for an example. • Optional components: • interfaces that are implemented by the enum • variable definitions (an enum is a class) • method definitions (an enum is a class) • Value-specific class bodies
enum Syntax Example public enum Foo { BAR(0), BAZ(1), QUUX(42); //values come first Foo(int val){ // constructor (private by default) this.val = val; } private int val = 0; // internal variable public void quuux(long val2) {return;} public String getDescription(){ switch(this){ case BAR: return “BAR-0”; break; case BAZ: return “BAZ-1”; break; default: return “”+val+“?”; } } }
A Few Points • An enum is a class, not a primitive type. • Enums extend java.lang.Enum, which is not an enumerated type. • Enumerated types are not integers. • Enumerated types can’t have public constructors. • Enumerated values are public, static, and final. • Enumerated values support comparison by == and equals().
More Points • Enums are comparable (have an order). • Enums provide toString(), returning the name of the value. • Enums provide a valueOf(String val) method to convert a String to a value. Recognises the names. • Enums provide a final method named ordinal(), which is the integer position of the value in the list. • Enums provide a values() method to support enumeration over the value list.
Inline Enums • You can declare an enum type within your class rather than at the top level if it is associated with that class. • To access it outside your class, make it visible (i.e., not private) and refer to it as YourClassName.EnumName
Iterating Over an Emun • First, you use the values() method to get an array of the values in the type. Name[] nameValues = Name.values(); • Then you can iterate in the normal way. • Or, use the following syntax: for(Name n : Name.values()){ whatever you want to do with each name; } • This is a variant of the new for/in syntax (qv).
Enum and Switch • Do the following: switch(enumerated value){ case value1: …; case value2: …; … case lastvalue: …; default: …; } • Java writes a jump-table to handle this.
Enum and Map • The values of an enum are Objects and can serve as indices of a map! • Suppose you have an enum called Foo, and corresponding values in some class called Bar, • You can create an EnumMap<Foo, Bar> around the two classes • An easy way that stores a full list of the enum is: EnumMap<Foo, Bar> theMap = EnumMap<Foo, Bar>(Foo.class); • Then all you need to do is initialise the values!
EnumSet • This is used to represent combinations of features that can occur independently. • First you define the enum enumName • Then you create an enumSet to represent the features. • There are a number of static member functions in EnumSet to do this.
EnumSet Static Member Functions • allOf(Class elementType); • complementOf(EnumSet e); • copyOf(Collection c); • noneOf(Class elementType); • of(one to five elements of the enum); • range(E from, E to); // avoid! If the enum changes, you’re hash! • clone(); • contains(E e); // to check whether e is present.
Boxing • Instances of primitive types are not objects. To create an object for a primitive type value, you have to wrap it in the corresponding reference type—Boolean, Character, Integer, Float, etc. • You must use reference types in Collections. This can be an utter pain. • Java has added autoboxing and unboxing. Those features automagically handle this wrapping and unwrapping via typecasts. • Don’t unbox null; you’ll get an exception! Also watch for problems with boolean expressions! • Test questions.
varargs • Advanced topic. • Just be aware that you can write Java methods that take multiple arguments of the same type. The number of arguments need not be predetermined.
Annotations • This is a standard way to annotate your code. There are three standard annotation types: • @Override just before a method definition indicates that it overrides a superclass method. • @Deprecated just before a definition indicates that its use is discouraged • @SuppressWarnings(value={array of “warnings”}) indicates that the following code should have specific compiler warnings turned off • You can also invent your own annotations and even annotate your annotations.
for/in • Also known as the enhanced for. • Gets rid of the need to use an Iterator and simplifies for loops. • Syntax: for(Object obj : collection){ operate on obj; // pseudo-code } • This also works with a generic collection with members that are of a given type. • String concatenation doesn’t work well, though. • Test questions.
for/in for Arrays • Suppose anArray is of type T[], where T is a reference or primitive type. Then you can loop through it as follows: for(T t : anArray){ // t gets set to anArray[i] // for each i from 0 to the end of the array operate on t // again pseudo-code } • Note the types must be compatible. The collection or array can be declared final (non-modifiable) for safety. • Test questions.
Static imports • This allows you to import a static class, variable, or enum and reference them with a simple name. • import static java.lang.System.out; • Now you can refer to out, rather than java.lang.System.out. • Also works for static methods (see Arrays and Collections), member types, and enums. • Wildcards (*) still work. • Test questions.
Formatting • Advanced topic. • import java.util.Formatter; • Allows you to use printf().
Threading • Advanced topic covered in a later lecture. • I won’t be testing your knowledge of Java 5 threading changes. • On the other hand, if you need to use threads in your final year project or other modules, Chris Knowles or I will be happy to discuss this material off-line.