【问题标题】:Java method returns from an array listJava 方法从数组列表返回
【发布时间】:2014-02-28 01:43:02
【问题描述】:

我想知道这甚至可能吗?以及执行此类操作的最佳方法是什么:

    private int NotifCountBg(int countstyle) {
    return new int[]{
            R.drawable.count_bevel,
            R.drawable.count_blue,
            R.drawable.count_green,
            R.drawable.count_orange,
            R.drawable.count_pink,
            R.drawable.count_purple,
            R.drawable.count_red,
            R.drawable.count_gray
         }[countstyle];
    }

【问题讨论】:

    标签: java android arrays optimization arraylist


    【解决方案1】:

    您可以为数组使用常量:

    private static final int[] STYLES = new int[]{ R.drawable.count_bevel, R.drawable.count_blue, 
        R.drawable.count_green, R.drawable.count_orange, R.drawable.count_pink,
        R.drawable.count_purple, R.drawable.count_red, R.drawable.count_gray };
    
    private int notifCountBg(final int countstyle) {
        return STYLES[countstyle];
    }
    

    【讨论】:

    • 这是最好的方法吗?
    • 你能定义“最佳”吗?
    • 我想知道如何优化代码,我的意思是优化。
    • 使用常量,数组 (STYLES) 被定义一次,而不是每次调用notifCountBg,所以它更优化
    【解决方案2】:

    使用枚举:摆脱索引、数组和类型化 (int) 常量。

    【讨论】:

    • 方法中使用的参数存在枚举,是私有方法,其他程序员无权访问
    • 我的意思是我不会用枚举来调用那个方法
    • 好的,虽然我无法想象调用者必须存储一个指向数组中某个位置的 int 而不是对 Enum 值本身的引用的原因
    猜你喜欢
    • 2014-12-14
    • 2011-04-14
    • 1970-01-01
    • 2013-05-27
    • 2015-07-20
    • 2011-06-30
    • 2016-06-10
    • 1970-01-01
    相关资源
    最近更新 更多