Search code examples
javavectorgetset

Unexpected output while getting element from Vector


I'm new in Vector usage in Java , and the problem here is that a Vector is not showing the output expected (Correct output: Pollo - Ercole This code output Ercole - Ercole)

.

Class Dipendente

public class Dipendente 
{
    private String Id;

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

Class Azienda

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());
    }

}

Correct output: Pollo - Ercole

This code output: Ercole - Ercole


Solution

  • You have to create a new instance of the object. Your code is anyway partial since we don't know what is az.dip. But assuming it is an instance of Dipendente. You need to do something like below for it to work.

        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());
    

    In your answer when you call setId the second time it is changing the value of the object that you were using earlier and hence you see a repeated entry.