有没有办法在Java中创建一个可以在其上使用[]的自定义类,类似于数组?

Efo*_*ren 9 java arrays class accessor

使用Java,有没有办法制作一个可以像数组一样使用[]访问器的自定义类?

正常数组

int[] foo = int[5];
foo[4] = 5;
print(foo[4]);
//Output: "5"
Run Code Online (Sandbox Code Playgroud)

自定义类

class Bar {
    //Custom class that uses index as a ref
}

Bar foo = new Bar(5);
foo.set(4, 5);
print(foo[4]);
//Output: "5"
Run Code Online (Sandbox Code Playgroud)

bel*_*lum 15

不,你不能[]为你的课程重载操作符Java.但是你可以为你的阵列创建getter.


T.J*_*der 6

不,Java没有任何运算符重载.