Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList writing over itself

Tags:

java

arraylist

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

like image 995
user1724416 Avatar asked May 19 '26 22:05

user1724416


1 Answers

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.

like image 88
Hovercraft Full Of Eels Avatar answered May 25 '26 04:05

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!