V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
platoo
V2EX  ›  Java

Java编程: 成员为数组类型,怎样对其操作才算合理?

  •  
  •   platoo · 2013-03-05 05:54:08 +08:00 · 5419 次点击
    这是一个创建于 4069 天前的主题,其中的信息可能已经有所发展或是发生改变。
    刚刚接触Java没多久,在实现一个类的时候,有一个成员(field)是数组类型,不知道怎么操作才算合理。
    代码:
    public class ArrayTest{
    private int length;
    private Object[] arr;

    public ArrayTest(int num){
    arr = new Object[num];
    length = num;
    }

    /* 移除指定位置的数据 */
    public void remove(int index){
    if ((index < length) && (arr[index - 1] != null)){
    arr[index - 1] = null;
    length--;
    }
    }

    /* 在指定位置添加数据 */
    public void add(int index, Object obj){
    if ((length < arr.length) && (arr[index - 1] == null)){
    arr[index - 1] = obj;
    length++;
    }
    }
    }

    我不明白的地方是:
    1、对于private成员需要使用setter来改变其值,那么数组成员的处理是否也是相同的呢?
    2、针对length,自增和自减运算的时候是否需要使用setter方法?
    10 条回复    1970-01-01 08:00:00 +08:00
    laskuma
        1
    laskuma  
       2013-03-05 06:19:55 +08:00 via iPhone
    同菜鸟
    实际情况下,一般不会把array暴露出去。比如当你implement stack或者heap的时候。如果需要提供内部数据结构 return一个copy吧。
    另外array自带length
    platoo
        2
    platoo  
    OP
       2013-03-05 06:58:21 +08:00
    @laskuma 也就是数组操作的时候,也要使用getter 和 setter方法来访问么?
    laskuma
        3
    laskuma  
       2013-03-05 07:09:57 +08:00 via iPhone
    @platoo 我觉得是完全不需要操作 这不是应该暴露给用户的东西
    laskuma
        4
    laskuma  
       2013-03-05 07:18:20 +08:00 via iPhone
    @platoo 我个人觉得再加个传入index拿到index上的object的getter就行了
    laskuma
        5
    laskuma  
       2013-03-05 07:22:19 +08:00 via iPhone
    @platoo 前面没有说清楚。。我个人觉得数组操作应该是 用户问send message 然后你再帮他做 用户不需要也不能知道你里面是如何implement的 就当成一个带有index的container。 不能直接用getter让用户直接获得数组 这样如果他改了里面的内容你会很难维护
    setter也是同理
    dongsheng
        6
    dongsheng  
       2013-03-05 08:32:06 +08:00
    这不就是ArrayList类吗?去看看ArrayList的源码就知道该怎么设计了。
    holmesabc
        8
    holmesabc  
       2013-03-05 08:52:53 +08:00   ❤️ 1
    ArrayList源码,搞定
    platoo
        9
    platoo  
    OP
       2013-03-07 09:00:32 +08:00
    @dongsheng 十分感谢!都不知道还有这么好的网站!
    ihuguowei
        10
    ihuguowei  
       2013-03-08 10:28:47 +08:00
    @dongsheng 谢谢,原来这边还有源码,再次谢谢提供这么好的资源。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2830 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 00:21 · PVG 08:21 · LAX 17:21 · JFK 20:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.