【问题标题】:Unexpected output while getting element from Vector [duplicate]从 Vector 获取元素时出现意外输出 [重复]
【发布时间】:2019-01-25 15:22:19
【问题描述】:

我是 Java 中 Vector 用法的新手,这里的问题是 Vector 没有显示预期的输出(正确的输出:Pollo - Ercole 此代码输出 Ercole - Ercole)

.

类依附

public class Dipendente 
{
    private String Id;

    void setId(String exId)
    {
    Id=exId;
    }
    String getId()
    {
    return Id;
    }
}

类异端

public class Azienda 
{      
    private Vector<Dipendente> Dip = new Vector<Dipendente>();
    public static void main(String[] args) throws IOException
    {
        Azienda az = new Azienda();
        az.dip.setId("Pollo");
        az.Dip.add(az.dip);
        az.dip.setId("Ercole");
        az.Dip.add(az.dip);

            //io.pf is System.out.println(strOut);

        az.io.pf(az.Dip.get(0).getId());
        az.io.pf(az.Dip.get(1).getId());
    }

}

正确的输出:Pollo - Ercole

此代码输出:Ercole - Ercole

【问题讨论】:

标签: java vector get set


【解决方案1】:

您必须创建对象的新实例。由于我们不知道 az.dip 是什么,因此您的代码无论如何都是不完整的。但假设它是 Dipendente 的一个实例。您需要执行以下操作才能使其正常工作。

    Azienda az = new Azienda();
    Dipendente dip = new Dipendente();
    dip.setId("Pollo");
    az.Dip.add(dip);
    Dipendente dip = new Dipendente();
    dip.setId("Ercole");
    az.Dip.add(az.dip);

        //io.pf is System.out.println(strOut);

    az.io.pf(az.Dip.get(0).getId());
    az.io.pf(az.Dip.get(1).getId());

在您第二次调用 setId 时,它会更改您之前使用的对象的值,因此您会看到重复的条目。

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2020-07-20
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多