I'm trying to add objects of my original class "day" that have integer values called "classment" to a linked list so I can keep track of which day comes first. The problem is, each time I add a day to this linked list and change the value of it's 'classment' to it's ranking in the list, all the previously added days also change the value of their 'classment' to the last one added. here's a simplification of the code
public class test {
public static void main(String[] args) {
LinkedList <day> days = new LinkedList<day>();
for(int i=0;i<5;i++){
day dayx = new day(); // Create a new day object here
dayx.classment = i;
days.add(dayx);
dayx = null;
}
for(int i=0;i<5;i++){
System.err.println(days.get(i).classment);
}
}
the result is just
4
4
4
4
4
I know this seems like a very simple problem that has many solutions online already, but all the results I found were in C++, and I couldn't translate the solution to java. It might even be me not fully understanding the concept of linked lists, but I did try regular arrays and I ended up with the same problem.
I just need them to be separate days with their separate variables and values. I want the result to simply be:
0
1
2
3
4
this is also a simplification of what the day class looks like:
public class day {
static Double startingRest=0.0, currentRest=0.0;
static int rownumber=-1,N=0;
static String date,title;
static int classment;
public day(){
rownumber=-1;
N=0;
startingRest=0.0;
currentRest=0.0;
}
}
You declared classment
as a static field of day
. That means only one copy of it is shared between all instances of the class. Each time you set a different value of any day.classment
it changes it for all instances of day.
Just remove the static
keyword from classment
and you should see different values per instance. The same goes for the other static
fields - make sure you really want them to be static.
Further to that, there are other modifiers you might consider to use instead of static. For example, you should decide if classment is a public or private field. If public then anyone can access it directly as in day.classment
, whereas if it's private you should provide a getter and setter (day.getClassment()
) for it.