Reputation: 41
I am making a HashMap with keys T and values Long, and my remove method (which is overrided from the AbstractCollection class) looks like this:
public boolean remove(Object o) {
if(denseBag.containsKey(o)){
if(denseBag.get(o) == 1L){
denseBag.remove(o);
} else {
Long removed = denseBag.get(o);
T theO = (T) o;
denseBag.replace(theO, removed, removed--);
}
} else {
return false;
}
I am getting the message: "Type safety: Unchecked cast from Object to T". I just want to make sure that it will work OK. Thank you.
Upvotes: 3
Views: 7495
Reputation: 86276
Your code will work correctly from all I can tell. If you can, I suggest you change the declaration of your method to
public boolean remove(T o)
With this you should not need the unchecked cast, which would make your code a little bit simpler. If you cannot and you believe us when we say your code is correct, use @SuppressWarnings("unchecked")
as Alexey Soshin said. And consider factoring the cast out into a separate method castToT(Object obj)
or what you wish to call it. The advantage of the tag is next time you get a friendly warning from your compiler or IDE, you know it’s not just an old one that you have chosen once to ignore.
Upvotes: 1
Reputation: 17721
It will. Java uses Object o signature in Collections for legacy reasons.
If that bothers you still, use @SuppressWarnings("unchecked")
.
You'll still have a lot of other troubles, though.
This will be ignored: removed--
, use --removed
Upvotes: 7