• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java arrays--why is this happening???

Vadatajs

Diamond Member
I'm trying to access a method of a class I defined that is in an array. Code:

public class Test1 {

private static Frame[] arr;
public static void main(String[] args) {

arr = new Frame[5];

for (int k = 0; k < 5; k++){
arr[k] = new Frame(k,k);
System.out.println(arr[k].getFrameNumber());
}

for (int k = 0; k< 5; k++){
System.out.println(arr[k].getFrameNumber());
}
}
}

the output is:
0
1
2
3
4 (good to this point, the end of the first for loop)
4
4
4
4
4 (wtf??? should match the top)

The Frame class is just a few integers, and they all have a default constructor (which would show up as -1 on the output), so I think I am initializing everything properly. I can't figure out why after I finish initializing the array, if I change one element, it changes the entire array. This behavior is counter to the examples and documentation I have seen so far, and also counter to my experience with arrays in c++.

EDIT: THe forum ate my [] bracket things. This is the only place I visit that doesn't have a code feature (and needs one badly)
 
I'm a bit of a Java n00b so if I'm wrong don't shoot me but here goes...

for (int k = 0; k < 5; k++){
arr[k] = new Frame(k,k);
System.out.println(arr[k].getFrameNumber());
}


It looks like you are creating the new Frame objects which arr points to within your first FOR loop. When that loop finishes these newly created objects go out of scope.

Am I right?
 
Originally posted by: Kilrsat
Are you sure the variables in the Frame class are not static?

no, they are static, should they not be?


Bingo!!!! That was it. Thank you so much. You just saved my ass.
 
this is the fram class, it works after getting rid of static

public class Frame {
private static int number = -1;
private static int enteredAtTry = 0;
private static int lastAccessTry = 0;
private static int numAccesses = 0;

public Frame(int Number, int initTry){
number = Number;
enteredAtTry = initTry;
lastAccessTry = initTry;
//access(initTry);
}

public int getFrameNumber(){
return number;
}

public void setFrameNumber(int init){
number = init;
}

public int getEnteredAt(){
return enteredAtTry;
}

public void setEnteredAt(int initTry){
enteredAtTry = initTry;
}

public void access(int currentTry){
//called by pager
numAccesses++;
lastAccessTry = currentTry;
}

public int getAccessCount(){
return numAccesses;
}
}
 
Back
Top