void lock(Mailbox<?> mb) { ... }
mb's generic references.
<T> void lock(Mailbox<T> mb) { ... }
<T> void lock(Mailbox<T> mb) T letter = mb.get();
Mailbox<blob> bmb = new Mailbox<blob>() Mailbox<spot> smb = new Mailbox<spot>()<blob>lock(bmb)// syntax error<spot>lock(smb)// Syntax error this.<blob>lock(bmb) this.<spot>lock(smb)
lock(bmb) // T is blob. lock(smb) // T is spot.
<T> addIfEmpty(Mailbox<T> mb, T letter)
T letter = mb.get()
if letter == null
mb.put(letter)
return null
return letter
T still can't appear in a new expression.
mb.put(newT())
Stack stringStk = new Stack() stringStk.push(new Object()) // Could be dangerous. String str = (String) stringStk.pop() // It is! Boom!
$ cat j.java
import java.util.Stack;
class t {
void moo() {
Stack intStk = new Stack();
intStk.push(new Integer(1));
}
}
$ javac j.java
Note: j.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:unchecked j.java
j.java:6: warning: [unchecked] unchecked call to push(E)
as a member of the raw type java.util.Stack
intStk.push(new Integer(1));
^
1 warning
$
import java.util.Stack
void moo()
Stack<Integer> intStk =
new Stack<Integer>()
intStk.push(new Integer(1))
void swap(Stack stk)
if stk.size() > 1
final Object e1 = stk.pop()
final Object e2 = stk.pop()
stk.push(e1) // warning
stk.push(e2) // warning
@SuppressWarnings("unchecked") annotation.
$ cat j.java
class s
@SuppressWarnings("unchecked")
void quiteSwap(Stack quietStk)
Object e1 = quietStk.pop()
Object e2 = quietStk.pop()
quietStk.push(e1)
quietStk.push(e2)
void noisySwap(Stack noisyStk)
Object e1 = noisyStk.pop()
Object e2 = noisyStk.pop()
noisyStk.push(e1)
noisyStk.push(e2)
$ javac -Xlint:unchecked j.java
j.java:18: warning: [unchecked] unchecked call to push(E)
as a member of the raw type java.util.Stack
noisyStk.push(e1);
^
j.java:19: warning: [unchecked] unchecked call to push(E)
as a member of the raw type java.util.Stack
noisyStk.push(e2);
^
2 warnings
$
-source javac command-line
option.
$ cat j.java
class s
void swap(Stack stk)
Object e1 = stk.pop()
Object e2 = stk.pop()
stk.push(e1)
stk.push(e2)
$ javac -Xlint -source 1.4 j.java
$