加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

有没有办法使用类似于数组的Java可以使用它的自定义类?

发布时间:2020-12-14 05:39:25 所属栏目:Java 来源:网络整理
导读:使用 Java,有没有办法使一个自定义类可以像数组一样使用[]访问器? 正常数组 int[] foo = int[5];foo[4] = 5;print(foo[4]);//Output: "5" 自定义类 class Bar { //Custom class that uses index as a ref}Bar foo = new Bar(5);foo.set(4,5);print(foo[4]);
使用 Java,有没有办法使一个自定义类可以像数组一样使用[]访问器?

正常数组

int[] foo = int[5];
foo[4] = 5;
print(foo[4]);
//Output: "5"

自定义类

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

Bar foo = new Bar(5);
foo.set(4,5);
print(foo[4]);
//Output: "5"

解决方法

不,你不能用Java重载你的类的[]运算符.但是您可以为阵列创建getter.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读