Home > Mobile >  Printing ArrayList contents of type Data gives the wrong output {Java}
Printing ArrayList contents of type Data gives the wrong output {Java}

Time:02-02

I have an ArrayList of type data(that stores a string called name and an integer called age). When printing the contents of the Arraylist, it prints the right age but the same name from the element that I've last added. Here is the PrintCollection method

import java.util.*;
import java.util.Iterator;
public class Lab5 {
  public static void PrintCollection(Collection<Data> c)
  {
    for (Iterator<Data> iter = c.iterator(); iter.hasNext();)
    {
        Data x = (Data)iter.next();
        x.Print();
    }
    System.out.println();
  }

}

and here is the class Data

import java.util.ArrayList;

public class Data 
{
    public static String name;
    private int age;
    Data(String n,int a)
    {
        name = n;
        age = a;
    }
    public String GetName()
    {
        return(name);
    }
    public void SetName(String n)
    {
        name = n;
    }
    public int GetAge()
    {
        return(age);
    }
    public void SetAge(int a)
    {
        age = a;
    }
    public void Print()
    {
        System.out.print(("(" GetName()));
        System.out.print(",");
        System.out.print(GetAge());
        System.out.print(") ");
    }
    public static void main(String args[])
    {
        ArrayList<Data> array = new ArrayList<Data>();
        Data x = new Data("Fred",21);
        array.add(x);
        Data y = new Data("Jo",43);
        array.add(y);
        Data z = new Data("Zoe",37);
        array.add(z);
        Lab5.PrintCollection(array);
    }

}

CodePudding user response:

That's because the name is not an instance variable, it belongs to the class definition, and each time you access it, you are referring to the same object reference; while the age is an instance variable, which means, for every instance of the class, there will be a distinct copy/reference of/to a different object (which is experienced by your GetAge() [bad naming.. use camelCaseForMethodNames] call).

See how instance variables are propagated here:

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.

CodePudding user response:

Just remove the keyword static in this line:

public static String name;

Also it's better to make it private too, to preserve encapsulation.

  •  Tags:  
  • Related