vgaldikas
vgaldikas

Reputation: 106

Prevent object stored in ArrayList from being over written

Basically I have to write a simple contact manager, and store objects in array list.

What frustrates me is that I have newContact method, which when called creates new instance of Contact, and stores it in ArrayList. The problem is that every time I call that method, all other objets in the list gets overwritten.

import java.util.ArrayList;
public class ContactManager {

  public static ArrayList<Contact> contactList = new ArrayList<Contact>();
  public static Contact[]c = {};

  public static void main(String[]args){
    newContact();
    newContact();

    System.out.println(contactList.get(1).getName());
    System.out.println(contactList.get(0).getName());
  }

  public static void newContact(){
    Contact c = new Contact();
    contactList.add(c);
  }
}

In Contact class constructore there is code that initializes the object's properties using Scanner class.

If in first call I Enter "John" and in second function call I enter "Peter", the above code will print out:

Peter Peter.

Why doesn't it prints out John Peter?

Only thing I can think of is that maybe Java stores only reference to object in arraylist, and that unlike variables objects don't get destroyed after function executes..

Any ways around this?

I hope this explains what I am trying to achieve.

PS. I know people hate people that as homework questions. But I am doing this as an extra, in order to learn new stuff. Original assignment barely asks to instantiate 5 objects and store them in ArrayList. And I have that done, now I am just trying to see if I could come up with more dynamic solution.

Contact class code:

import java.util.Scanner;

public class Contact{

private static String name, number;

//constructor will ask to enter contact details
public Contact(){
    Scanner in = new Scanner(System.in);

    System.out.println("Enter name:");
    name = in.next();

    System.out.println("Enter number:");
    number = in.next();
}

//getters and setters

public static String getName(){
    return name;
}

public static String getNumber(){
    return number;
}

public static void setName(String newName){
    name = newName;
}

public static void setNumber(String newNumber){
    number = newNumber;
}

}

Upvotes: 0

Views: 356

Answers (1)

Jeff Foster
Jeff Foster

Reputation: 44706

It's because the members in the Contact class are static. That means that all Contact instances share the same name and number. You should make them instance members so that each time you do new Contact you get a new copy of these variables.

Upvotes: 1

Related Questions