问题
So I'm trying to run this simple program here:
import java.util.*;
class StackDemo
{
public static void main(String[] args) {
Stack s = new Stack();
s.push(5);
s.push("dog");
System.out.print(s);
}
}
StackDemo.java
uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked
for details.
Process completed.
It displays the expected result, which is "[5, dog]"
but I don't understand that message on the Build Output window.
What could possibly be wrong here?
回答1:
Stack
is a generic class, which you can use, if you wish, to store objects of a specific type (e.g., Stack<String>
would be used to store strings). Using bare classes, without a type specifier is usually considered a bad practice, as you're losing the type safety of the collection.
If there is indeed a usecase where you'd like to store both 5
and "dog"
in your stack, you should define your stack with the greatest common denominator between the two - Object
:
Stack<Object> s = new Stack<>();
回答2:
Stack is a legacy class but the warning is because you haven't use generics and the compiler cannot check whether you have added the right types or not.
Given you have mixed the types, in a real program I would hope this is bug.
来源:https://stackoverflow.com/questions/21157409/stack-unchecked-unsafe-operations