Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this an unchecked cast?

 
Dave Tong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49382
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic