Java中是否有相当于C#的索引器?

Chr*_*ove 16 c# java

我想用Java做到这一点.可能吗?

public string this[int pos]
    {
        get
       {
            return myData[pos];
        }
        set
       {
            myData[pos] = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 26

不能.您不能在Java中重载任何运算符,包括索引.(String重载+,但这已经融入语言规范.)

只有数组支持[]语法.

你通常会改写方法:

public String getValue(int position) {
    return myData[position];
}

public void setValue(int position, String value) {
    myData[position] = value;
}
Run Code Online (Sandbox Code Playgroud)

  • 你伤了我的心,Java。为什么有人会为此放弃 C#? (3认同)