









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










Review of Java Language Constructs
Primitive types, variables, constants, operators If-else, switch, while, for
Object instances Creating objects with new Object references The null reference Instance data, class (static) data Methods Parameters, return values, polymorphism
Java Language Constructs
Enumerated Types
New type of variable with set of fixed values
Establishes all possible values by listing them Supports values(), valueOf(), name(), compareTo()… Can add fields and methods to enums
Example
public enum Color { Black, White } // new enumeration Color myC = Color.Black; for (Color c : Color.values()) System.out.println(c);
When to use enums
Natural enumerated types – days of week, phases of the moon, seasons Sets where you know all possible values
Generics – Motivating Example
Utility classes handle arguments as Objects Objects must be cast back to actual class Casting can only be checked at runtime
class A { … } class B { … } List myL = new List(); myL.add(new A()); // Add an object of type A … B b = (B) myL.get(0); // throws runtime exception // java.lang.ClassCastException
Solution – Generic Types
Provides abstraction over types Can parameterize classes, interfaces, methods Parameters defined using
public class foo<X, Y, Z> { … } List
Readability & robustness
Autoboxing & Unboxing
Data value Object (of matching class) Data types & classes converted Boolean, Byte, Double, Short, Integer, Long, Float
ArrayList
Iterator Interface
public interface Iterator { boolean hasNext( ); Object next( ); void remove( ); // optional, called once per next( ) }
Iterator i = myCollection.iterator( ); while (i.hasNext( )) { myCollectionElem x = (myCollectionElem) i.next( ); }
Enhanced For Loop
ArrayList
roster.add("John");
roster.add("Mary");
// using an iterator
for (Iterator
System.out.println(it.next( ));
// using for loop
for (String student : roster)
System.out.println(student);
Comparable Interface
Comparable
public int compareTo(Object o) A.compareTo(B) returns Negative if A < B, 0 if A == B, positive if A > B
Properties
Referred to as the class's natural ordering Can sort using Collections.sort( ) & Arrays.sort( ) Example: Collections.sort(myList); Can use as keys in SortedMap & SortedSet Consistency w/ equals( ) strongly recommended x.equals(y) if and only if x.compareTo(y) == 0
Example (comparableExample)
2-D Arrays of Primitives
int [ ][ ] data = new int[3][4];
int [ ][ ] ragged = new int[2][ ]; ragged[0] = new int[3]; ragged[1] = new int[1];
2-D Arrays of Objects
String [ ][ ] data = new String[3][4];