0

I got a problem I am currently stuck on. Essentially what I want to do is I want to have a variable array, have that be overwritten, saying it to a different variable, then having the initial variable be overwritten again, saving it to yet again a different variable and comparing the two saved variables.

The code in mind goes as follows:

int[] Item1 = {1,1}
int[] SavedItem1;
int[] SavedItem2;

Program1();
SavedItem1 = Item1; 
Program2();
SavedItem2 = Item1;

player.sm("The value is: " + SavedItem1[0] + " and " + SavedItem2[0] + ".");

public static void Program1() { Item1 = {2,2,2,2,2};}
public static void Program2() { Item1 = {3,4,4,5,5};}

but what this returns ingame is: The value is 1 and 1, clearly it does not overwrite the value in the programs, I don't understand why not and I don't know how to solve this problem, what would be the correct way to do what I am trying to do here? (The correct output is: The value is 2 and 3.)

Thank you all

-Antoine

2 Answers2

0

I think this is what you want: From the - Javadoc

set public E set(int index, E element)

Replaces the element at the specified position in this list with the specified element.

Specified by: set in interface List

Overrides: set in class AbstractList

Parameters: index - index of the element to replace element - element to be stored at the specified position

Returns: the element previously at the specified position Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

So you can simply override the value at a specific location...

Cowboy Farnz
  • 329
  • 2
  • 11
0

When you assign an array to another they both point to the same array. Hence in your code SavedItem1 and SavedItem2 are essentially the same, which point to the 1st element of array Item1.

And public static void Program1() { Item1 = {2,2,2,2,2};}, the Item1 here is in a different scope. So changes to it wll not effect the Item1 in the main method.

To achieve what you are trying to do return the new array and assign it to Item1.

public static int[] Program1() { return new int [] {2,2,2,2,2};   

Likewise for Program2 as well. Or else to override the Item1 variable make it scoped appropriately (i.e, above both your Main and methods Program1 and Program2)

Antho Christen
  • 1,369
  • 1
  • 10
  • 21