Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of C# indexer in Java?

Tags:

I want to do this in Java. Is it possible?

public string this[int pos]
    {
        get
       {
            return myData[pos];
        }
        set
       {
            myData[pos] = value;
        }
    }
like image 621
Christophe Debove Avatar asked Nov 15 '12 18:11

Christophe Debove


2 Answers

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;
}
like image 182
Jon Skeet Avatar answered Oct 01 '22 02:10

Jon Skeet


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.

like image 25
Sergey Kalinichenko Avatar answered Oct 01 '22 02:10

Sergey Kalinichenko