user1724416
user1724416

Reputation: 954

ArrayList writing over itself

Hello i have some simplified code here showing the problem i have. Basically i can not seem to add to the end of the ArrayList instead it writes over itself. Please help

Main

public class Main {

public static void main(String[] args) {
    HolderOfList h = new HolderOfList();
    h.addToHolder(new Num(2, "Bob"));
    h.addToHolder(new Num(3, "Cat"));
    h.addToHolder(new Num(4, "Dog"));
    h.printAll();
}
}

Class holding ArrayList

import java.util.ArrayList;
import java.util.List;

public class HolderOfList {
List<Num> num;

public HolderOfList() {
    num = new ArrayList<Num>();
}

void addToHolder(Num n) {
    num.add(n);
}

void printAll() {
    for (int i = 0; i < num.size(); i++) {
        System.out.println(num.get(i).getI() + num.get(i).getStr());
    }
}
}

Element held in the ArrayList

public class Num {

private static String str;
private static int i;

public Num(int i, String str) {
    this.str = str;
    this.i = i;
}

String getStr() {
    return str;
}

int getI() {
    return i;
}

}

The desired output is 2Bob 3Cat 4Dog

but all i get is

4Dog 4Dog 4Dog

I have a larger scale project with this problem in it any ideas?

Thank You in advance

Upvotes: 3

Views: 164

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Get rid of the static modifiers for your Num variables as they're making it so that all Num instances effectively share the same single variable (not really as they're actually variables of the class, but the behavior is the same). Make them instance (non-static) variables instead.

In other words, change this:

public class Num {
  private static String str;
  private static int i;

to this:

public class Num {
  private String str;
  private int i;

Lesson learned: use the static modifier sparingly and only when it makes sense to do so. It doesn't make sense here.

Upvotes: 5

Related Questions