【问题标题】:Stack in Java and object cannot be converted to java.lang.StringJava中的堆栈和对象无法转换为java.lang.String
【发布时间】:2020-07-28 21:26:43
【问题描述】:

如何引用这段代码?

    class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {

        Person thePerson1 = new Person("Name1", "Surname1", 1901);
        Person thePerson2 = new Person("Name2", "Surname2", 1901);
        Person thePerson3 = new Person("Name3", "Surname3", 1901);
        Person thePerson4 = new Person("Name4", "Surname4", 1901);
        Person thePerson5 = new Person("Name5", "Surname5", 1901);

        Stack<String> thestack = new Stack<String>();
        thestack.push(thePerson1);
        thestack.push(thePerson2);
        thestack.push(thePerson3);
    }
}

我有一个问题: 不兼容的类型:Person 无法转换为 java。朗。字符串,第 56 行 一些消息已被简化;使用 -Xdiags 重新编译:详细以获取完整输出,第 -1 行

如果我想使用thePerson1、thePerson2等,如何改变Stack的类型?

【问题讨论】:

  • Stack&lt;Person&gt; thestack = new Stack&lt;Person&gt;();
  • thestack.push(thePerson1.toString()); 取决于您要执行的操作,但我猜您应该更改堆栈类型。

标签: java arrays stack


【解决方案1】:

您应该将其定义为Stack&lt;Person&gt;,而不是Stack&lt;String&gt;

Stack<Person> thestack = new Stack<Person>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多