wood burning stoves 2.0*
The moose likes Java in General and the fly likes Why is this an unchecked cast? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why is this an unchecked cast?" Watch "Why is this an unchecked cast?" New topic
Author

Why is this an unchecked cast?

Dave Tong
Greenhorn

Joined: Jul 06, 2005
Posts: 10
And how do I fix it without changing the method signature of foo?

import java.util.Vector;
public class NewClass {
public NewClass() {
Vector<Object> vec = new Vector<Object>();
foo(vec);
}
public void foo(Object bar) {
Vector<Object> v = (Vector<Object> bar;
}
}

NewClass.java:8: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Vector<java.lang.Object>
Vector<Object> v = (Vector<Object> bar;
1 warning
Bupjae Lee
Ranch Hand

Joined: May 14, 2007
Posts: 107
Unchecked cast means 'although this cast is vaild, and no ClassCastException is thrown here, other point would throw ClassCastException involving using this object'.

For example:



This happens because java virtual machine can't recognize the difference between Vector<String> and Vector<Integer> - JVM recognize both just Vector
[ May 16, 2007: Message edited by: Bupjae Lee ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37991
    
  22
I would suggest using Object as a parameter type is too vague; you are leaving yourself open to ClassCastException problems. Similarly using <Object> as a generic type is also too vague.

Go through the generics part of the Java Tutorial. You may end up having to change the parameter to "Vector<? extends XYZ>".

BTW: Why are you using Vector rather than ArrayList?
Dave Tong
Greenhorn

Joined: Jul 06, 2005
Posts: 10
What I'm doing is sending a message to an asynchronous service.
The service emits a Notification when the response arrives.
So I'm passing a Vector (or other List) as the Handback object to the Notification handler and calling wait.

The Notification Listener is called when the Notification arrives.
It gets the UserData from the Notification and adds it to the handback Vector, then calls vector.notify()

The caller wakes up and has the response in its vector.
Apart from the compiler b!tching at me it all works fine.
 
Consider Paul's rocket mass heater.
 
subject: Why is this an unchecked cast?
 
Similar Threads
Dynamic GridLayout Paint
n-dimensioned array in Java
Casting and Generics
What the hell is a serialized object?
Legacy Code to Generics