Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.
Object Class Employee e = new Employee(); e.clear(); // ERROR
e = null; e.setSalary(20000); // ERROR
int short long byte
char float double boolean null type void is not a type
int Rectangle Shape String[] double[][]
null new Rectangle(5, 10, 20, 30); "Hello" new int[] { 2, 3, 5, 7, 11, 13 } null S is a subtype of T if
Object Cloneable or Serializable
null type and T is not a primitive type Container is a subtype of Component JButton is a subtype of Component FlowLayout is a subtype of LayoutManager ListIterator is a subtype of Iterator Rectangle[] is a subtype of Shape[] int[] is a subtype of Object int is not a subtype of long long is not a subtype of int int[] is not a subtype of Object[]
Rectangle[] is a subtype of Shape[] Rectangle[] value to Shape[] variable:
Rectangle[] r = new Rectangle[10]; Shape[] s = r;
r and s are references to the same array s[0] = new Polygon();
compiles ArrayStoreException at runtime
Integer Short Long Byte Character Float Double Boolean
ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(13); // calls new Integer(13) int n = numbers.get(0); // calls intValue();
enum Size { SMALL, MEDIUM, LARGE }
Size imageSize = Size.MEDIUM;
if (imageSize == Size.SMALL) . . .public static final int SMALL = 1; public static final int MEDIUM = 2; public static final int LARGE = 3;
enum equivalent to class with fixed number of instances
public class Size
{
private /* ! */ Size() { }
public static final Size SMALL = new Size();
public static final Size MEDIUM = new Size();
public static final Size LARGE = new Size();
} enum types are classes; can add methods, fields, constructors
e is a Shape:
if (e instanceof Shape) . . .
Shape s = (Shape) e;
e Shape e is null, test returns false (no exception) Class ClassgetClass method gets class of any object Class Class object describes a type
Object e = new Rectangle(); Class c = e.getClass(); System.out.println(c.getName()); // prints java.awt.Rectangle
Class.forName method yields Class object:
Class c = Class.forName("java.awt.Rectangle"); .class suffix yields Class object:
Class c = Rectangle.class; // java.awt prefix not needed
Class is a misnomer: int.class, void.class,Shape.class Employee Object vs. the Employee.class Object
e is a Rectangle:
if (e.getClass() == Rectangle.class) . . .
== Class object for every class instanceof to test for subtypes:
if (e instanceof Rectangle) . . .
getClass to an array double[] a = new double[10];
Class c = a.getClass();
if (c.isArray())
System.out.println(c.getComponentType());
// prints double
getName produces strange names for array types
[D for double[])
[[java.lang.String; for String[][]
Object String toString() boolean equals(Object otherObject) Object clone() int hashCode() toString MethodRectangle.toString returns something like
java.awt.Rectangle[x=5,y=10,width=20,height=30]
toString used by concatenation operator aString + anObject
means
aString + anObject.toString()
Object.toString prints class name and object address
System.out.println(System.out)yields
java.io.PrintStream@d2460bf
PrintStream didn't override toString: toString Methodpublic class Employee
{
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ "]";
}
...
}
Employee[name=Harry Hacker,salary=35000]
toString in Subclasspublic class Manager extends Employee
{
public String toString()
{
return super.toString()
+ "[department=" + department + "]";
}
...
}
Manager[name=Dolly Dollar,salary=100000][department=Finance]
equals Methodequals tests for equal contents == tests for equal location ArrayList.indexOf
/**
Searches for the first occurrence of the given argument,
testing for equality using the equals method.
@param elem an object.
@return the index of the first occurrence
of the argument in this list; returns -1 if
the object is not found.
*/
public int indexOf(Object elem)
{
if (elem == null)
{
for (int i = 0; i < size; i++)
if (elementData[i] == null) return i;
}
else
{
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i])) return i;
}
return -1;
}
equals Methodpublic class Employee
{
public boolean equals(Object otherObject)
// not complete--see below
{
Employee other = (Employee)otherObject;
return Objects.equals(name, other.name)
&& salary == other.salary;
}
...
}
Object parameter to subclass == for primitive types, Objects.equals (null-safe version of Object.equals) for object fields
equals in Subclassequals on superclass
public class Manager
{
public boolean equals(Object otherObject)
{
Manager other = (Manager)otherObject;
return super.equals(other)
&& department.equals(other.department);
}
}
equals Methods are Simplepublic boolean equals(Object o)
{
if (o == this) return true;
if (!(o instanceof Set)) return false;
Collection c = (Collection) o;
if (c.size() != size()) return false;
return containsAll(c);
}
Object.equalsMethodObject.equals tests for identity:
public class Object
{
public boolean equals(Object obj)
{
return this == obj;
}
...
}
equals if you don't want to inherit that behavior equals Methodx.equals(x) x.equals(y) if and only if y.equals(x) x.equals(y) and y.equals(z), then x.equals(z) x.equals(null) must return false Employee.equalsnull:
if (otherObject == null) return false otherObject not an Employee false (because of symmetry) instanceof
if (!(otherObject instanceof Employee)) return false;
// don't do this for non-final classes
e, m have same name, salary
e.equals(m) is true (because m instanceof Employee)
m.equals(e) is false (because e isn't an instance of Manager) if (getClass() != otherObject.getClass()) return false;
equals Methodpublic boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
...
}
hashCode method used in HashMap, HashSet int from an object String
int h = 0; for (int i = 0; i < s.length(); i++) h = 31 * h + s.charAt(i);
"eat" is 100184 "tea" is 114704
equals:
if x.equals(y), then x.hashCode() == y.hashCode() Object.hashCode hashes memory address equals public class Employee
{
public int hashCode()
{
return Objects.hash(name, salary);
}
...
}
copy = e) makes shallow copy Employee cloned = e.clone();
Object.clone makes new object and copies all fields Object.clone is protected clone to be public
public class Employee
{
public Employee clone()
{
return (Employee) super.clone(); // not complete
}
...
}
Cloneable Interface
Object.clone is nervous about cloning Cloneable interface
public interface Cloneable
{
}
if x implements Cloneable
Object.clone throws CloneNotSupportedException clone Methodpublic class Employee
implements Cloneable
{
public Employee clone()
{
try
{
return (Employee) super.clone();
}
catch(CloneNotSupportedException e)
{
return null; // won't happen
}
}
...
}
public Employee clone() throws CloneNotSupportedException
{
return (Employee) super.clone();
}
clone makes a shallow copy
clone make a deep copy?
Wouldn't work for cyclic data structures
public class Employee
implements Cloneable
{
public Object clone()
{
try
{
Employee cloned = (Employee)super.clone();
cloned.hireDate = (Date)hiredate.clone();
return cloned;
}
catch(CloneNotSupportedException e)
{
return null; // won't happen
}
}
...
}
Object.clone is paranoid
clone is protected Cloneable objects
clone throws checked exception Manager.clone must be defined if Manager adds mutable fields clone, redefine clone Employee[] staff = new Employee[2]; staff.add(new Employee(...)); staff.add(new Employee(...));
ObjectOutputStream:
ObjectOutputStream out
= new ObjectOutputStream(
new FileOutputStream("staff.dat"));
out.writeObject(staff); out.close();
Employee doesn't have to define any method Serializable interface
BufferedImage BufferedImage field?
transient:
private transient BufferedImage image;
private (!) methods
private void writeObject(ObjectOutputStream out)
private void readObject(ObjectInputStream in) writeDefaultObject/readDefaultObject Class object reveals
Class getSuperclass() Class[] getInterfaces() Package getPackage() Field[] getDeclaredFields() Constructor[] getDeclaredConstructors() Method[] getDeclaredMethods() Math class:
Field[] fields = Math.class.getDeclaredFields();
for (Field f : fields)
if (Modifier.isStatic(f.getModifiers()))
System.out.println(f.getName());
Rectangle
constructors:
for (Constructor c : cons)
{
Class[] params = cc.getParameterTypes();
System.out.print("Rectangle(");
boolean first = true;
for (Class p : params)
{
if (first) first = false; else System.out.print(", ");
System.out.print(p.getName());
}
System.out.println(")");
}
Rectangle() Rectangle(java.awt.Rectangle) Rectangle(int, int, int, int) Rectangle(int, int) Rectangle(java.awt.Point, java.awt.Dimension) Rectangle(java.awt.Point) Rectangle(java.awt.Dimension)
Rectangle.contains(int, int):
Method m = Rectangle.class.getDeclaredMethod( "contains", int.class, int.class);
Rectangle constructor:
Constructor c = Rectangle.class.getDeclaredConstructor();
getDeclaredMethod, getDeclaredConstructor are varargs methods
null for static methods)
System.out.println("Hello, World") the hard way.
Method m = PrintStream.class.getDeclaredMethod( "println", String.class); m.invoke(System.out, "Hello, World!");
invoke is a varargs method
Class c = obj.getClass(); Field f = c.getDeclaredField(name); f.setAccessible(true);
Object value = f.get(obj); f.set(obj, value);
int currentPosition=0 int newPosition=-1 int maxPosition=13 java.lang.String str=Hello, World! java.lang.String delimiters=, boolean retDelims=false boolean delimsChanged=false char maxDelimChar=, --- int currentPosition=5 . . .
Array class Object value = Array.get(a, i); Array.set(a, i, value);
int n = Array.getLength(a);
Object a = Array.newInstance(type, length);
ArrayList<int>public class ArrayList<E>
{
public E get(int i) { . . . }
public E set(int i, E newValue) { . . . }
. . .
private E[] elementData;
}
S a subtyoe of T, ArrayList<S> is not a subtype of ArrayList<T>.public class Utils
{
public static <E> void fill(ArrayList<E> a, E value, int count)
{
for (int i = 0; i < count; i++)
a.add(value);
}
}
ArrayList<String> ids = new ArrayList<String>(); Utils.fill(ids, "default", 10); // calls Utils.<String>fill
public static <E> void append(ArrayList<E> a, ArrayList<E> b, int count)
{
for (int i = 0; i < count && i < b.size(); i++)
a.add(b.get(i));
}
Cannot append an ArrayList<Rectangle> to an ArrayList<Shape>
public static <E, F extends E> void append(
ArrayList<E> a, ArrayList<F> b, int count)
{
for (int i = 0; i < count && i < b.size(); i++)
a.add(b.get(i));
}
extends means "subtype", i.e. extends or implementsE extends Cloneable & Serializableappend never uses type F. Can simplify with wildcard:
public static <E> void append(
ArrayList<E> a, ArrayList<? extends E> b, int count)
{
for (int i = 0; i < count && i < b.size(); i++)
a.add(b.get(i));
}
ArrayList<? extends E>.setmethod has the form
? extends E add(? extends E newElement)
? extends E because ? is unknown
get:
? extends E get(int i)E? super F matches any supertype of Fpublic static <F> void append(
ArrayList<? super F> a, ArrayList<F> b, int count)
{
for (int i = 0; i < count && i < b.size(); i++)
a.add(b.get(i));
}ArrayList<? super F>.add:
boolean add(? super F newElement)
F (but not a supertype!)
public static <E extends Comparable<E>> E getMax(ArrayList<E> a)
{
E max = a.get(0);
for (int i = 1; i < a.size(); i++)
if (a.get(i).compareTo(max) > 0) max = a.get(i);
return max;
}
E extends Comparable<E> so that we can call compareToArrayList<GregorianCalendar>GregorianCalendar does not implement Comparable<GregorianCalendar>, only Comparable<Calendar>public static <E extends Comparable<? super E>> E getMax(ArrayList<E> a)
Object if unboundedArrayList<E> becomes
public class ArrayList
{
public Object get(int i) { . . . }
public Object set(int i, Object newValue) { . . . }
. . .
private Object[] elementData;
}
getMax becomes
public static Comparable getMax(ArrayList a) // E extends Comparable<? super E> erased to Comparable
a.add(new E()); // Error--would erase to new Object()public static <E> void fillWithDefaults(ArrayList<E>,
Class<? extends E> cl, int count)
throws InstantiationException, IllegalAccessException
{
for (int i = 0; i < count; i++)
a.add(cl.newInstance());
}
fillWithDefaults(a, Rectangle.class, count)
Comparable<E>[] is illegal. Remedy: ArrayList<Comparable<E>>GregorianCalendar cannot implement Comparable<GregorianCalendar> since it already implements Comparable<Calendar>, and both erase to Comparable
| Name in Design Pattern | Actual Name (Beans) |
| Client | Builder tool |
| Facade | Main bean class with which the tool interacts |
| SubsystemClass | Class used to implement bean functionality |
b.propertyName = value
calls setter variable = b.propertyName
calls getter public X getPropertyName() public void setPropertyName(X newValue)
propertyName with actual name
(e.g. getColor/setColor) boolean properties:
public boolean isPropertyName()
getColor -> color getURL -> URL
jar cvfm CarBean.jar CarBean.mf *.class
stateChanged event of slider carBean1.setX(jSlider1.getValue());