Reputation: 6296
I want to do this in Java. Is it possible?
public string this[int pos]
{
get
{
return myData[pos];
}
set
{
myData[pos] = value;
}
}
Upvotes: 23
Views: 9702
Reputation: 6657
You can do directly the same way but you can use Collection framework
of Java
which provice similary kind of functionality which you want i suppose. Such as List
, Set
etc.
Upvotes: 0
Reputation: 10957
I don't think so. AFAIK the usual Java approach to this are public string get(int pos)
and public void set(int pos, String value)
methods.
Upvotes: 0
Reputation: 1500903
No. You can't overload any operators in Java, including indexing. (String
overloads +
, but that's baked into the language specification.)
Only arrays support []
syntax.
You'd generally write methods instead:
public String getValue(int position) {
return myData[position];
}
public void setValue(int position, String value) {
myData[position] = value;
}
Upvotes: 33
Reputation: 726639
No, Java does not have anything similar to C#'s indexers or overloaded operators. That is the most likely reason why the function call syntax is used in String.charAt
, List.get
, Map, put
, and so on.
Upvotes: 3