Stack - unchecked/unsafe operations

2019-08-03 15:27发布

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?

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-03 15:45

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.

查看更多
狗以群分
3楼-- · 2019-08-03 16:01

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<>();
查看更多
登录 后发表回答