Object-Oriented Programming with Java Lecture Notes

27 March 2008 • Advanced Generics


Outline

Remember This?

Generic Methods

Calling Generic Methods

Type Inference

Generic Classes and Methods

Generic-Method Mutation

Old Code

Example

$ 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

$ 

Unchecked Warnings

Rewriting Old Code

Ignoring Unchecked Warnings.

Example

$ 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

$ 

Ignoring Unchecked Warnings..


This page last modified on 4 March 2008.

Creative
    Commons License