I have a problem where the data I enter is writing to all elements in a List instead of one and I’m really struggling to figure out why, thanks for the help anyone who can..
public class Courts implements Serializable {
private static final long serialVersionUID = 1;
List<String[][]> allCourts = new ArrayList<String[][]>(10);
}
And here is the method I’m using to alter this List
public String bookCourt(int courtNo,int day,int time) throws RemoteException{
String [][] tmp = court.allCourts.get(courtNo - 1);
if(tmp[day-1][time-1].equals("Available")){
tmp[day-1][time-1] = logged.name;
court.allCourts.set(courtNo - 1,tmp);
return "Your booking has been accepted, booking is on (" + court.courtNames[courtNo - 1] +
"),(" + court.days[day - 1] + ") at ("
+ court.times[time - 1] + ").\n";
}
return "Court already taken by " + tmp[day-1][time-1] + ".\n";
}
Format came out a bit wonky there, sorry about that..
What I think this should do is get the 2D array from the allCourts list at courtNo-1 index, check if the String at the specified position is “Available” and if it is set it to logged.name.
Then it should take this updated 2D array and overwrite the array in the List with it, only problem is that it writes the name or array to every element in the allCourts List and I do not know why, again I appreciate any help yous can provide me.
I’m not sure why it is doing the specific behavior you mentioned, since to me, it looks like it should just be throwing NullPointerExceptions due to lack of initialization. I’m guessing that somewhere, you’re initializing
allCourtsso that all elements are the same array.However, some things to keep in mind. In Java, arrays are just an object like anything else.
tmpis a reference to the array object which is also referenced by the reference stored at positioncourtNo-1inallCourts. Calling set does not overwrite the array, it overwrites the array reference, which is already equal totmp. So thecourt.allCourts.set(courtNo - 1,tmp);does nothing.