Reputation: 668
I am a C++/C# developer but I am new to Java. I am trying to implement setters and getters for an array of strings within a basic class, like so:
private String[] values = new String[35];
public String get_val(int idx)
{
return values[idx];
}
public void set_val(int idx, String val)
{
values[idx] = val;
}
When I call the set_val
function, it will update the value of the nth string. After running code such as the following:
row.set_val(0, row.get_val(0) + "1");
row.set_val(0, row.get_val(1) + "2");
row.set_val(0, row.get_val(2) + "3");
string foo = row.get_val(0);
By the time the string foo = row.get_val(0);
, the 0th value is back to its original value. Am I missing a concept with arrays and Java? This seems like pretty straight forward code.
Thanks in advance!
Upvotes: 1
Views: 93
Reputation: 2992
This should work just fine as programmed, but I would heavily consider using the ArrayList structure built into java instead. It's pre-cooked into java, and if you initialize the size,
private List<String> strings = new ArrayList<String>(35);
you should get the same (if not better runtime performance, and not need to do any bounds checking)
private final MAX_SIZE = 35;
public String get_val(int idx)
{
if(idx<strings.size())
return strings.get(idx);
else
return null;
}
public void set_val(int idx, String val)
{
if(idx<MAX_SIZE)
strings.add(val,idx);
else
//throw an exception if that's how you really want to do it
}
Upvotes: 1