Christophe Debove
Christophe Debove

Reputation: 6296

Is there an equivalent of C# indexer in Java?

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

Answers (4)

Bhavik Ambani
Bhavik Ambani

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

Honza Brestan
Honza Brestan

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

Jon Skeet
Jon Skeet

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

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions