【问题标题】:Java : To write a method that can be applied on any kind of arrayJava : 编写一个可以应用于任何一种数组的方法
【发布时间】:2018-05-23 16:32:45
【问题描述】:

您好,感谢您注意到我的问题。我想写一个可以被不同类型的数组使用的方法。但我的代码总是这样:

public int indexOf_1(int[] a,int b){
    //Find the first matched result and return, otherwise report -1
    int index = -1;
    for(int j=0;j<a.length;j++){
        if (a[j]==b) 
        {index=j;}
    }
    return index;
}

public int indexOfChar_1(char[] a,int b){
    //Consider merged to the previous method?
    int index = -1;
    for(int j=0;j<a.length;j++){
        if (a[j]==b) 
        {index=j;}
    }
    return index;
}

这似乎是多余的,我对这样的代码重复完全不满意。有没有办法为各种数组编写搜索方法以避免在这种情况下重复?谢谢!

【问题讨论】:

  • 正如您在Arrays 中看到的,对于每个原始类型和对象,都必须复制代码。 BTW if (a[j] == b) return j; 会更快。
  • 顺便说一句,您的代码返回数组中的 last 匹配元素,而不是第一个。要返回第一个,请将 index=j 替换为 return j

标签: java arrays


【解决方案1】:

不幸的是,由于数组和 JVM 的工作方式,这无法减少。甚至泛型也无济于事,因为在没有显式转换的情况下,int[] 无法安全地转换为 Object[]

这看起来像一个常见的 util 函数。如果您对代码重复不满意,可以考虑使用提供此功能的众多库之一。 Guava 和 Commons-Lang 是少数。

Guava 将它们放在与primitive type 相关的类中。 Commons-Lang 将它们排列在ArrayUtils 类中

例如

Bytes.indexOf(byteArray, (byte) 2);
Ints.indexOf(intArray, 22);
ArrayUtils.indexOf(intArray, 6);

【讨论】:

    【解决方案2】:

    你可以使用Object[],但你可能不想使用==,因为它会比较对象的身份而不是值,你可能想使用.equals()。 (除非您知道该值始终是 charint)也许这样:

    public int indexOf(Object[] a, int b) {
        int index = -1;
        for (int j = 0; j < a.length; j++) {
            if (a[j].equals(b)) {
                index = j;
            }
        }
        return index;
    }
    

    【讨论】:

    • int[] 不能转换为 Object[]
    • 这正是我要写的。完全同意!
    • int 可以是Object[] 中的一个元素。不管有什么其他方法,你都必须强制类型
    【解决方案3】:
    public static <T> int index_Of(Object[] input,T value){
        //Find the first matched result and return, otherwise report -1
        for(int j=0;j<input.length;j++){
            if(input[j].equals(value))
                return j;
        }
        return -1;
    }
    

    您可以概括处理各种数组的方法。但是,请多注意类型。如果要使用 Object 引用原始类型,则在声明原始类型数组时,需要使用引用类型。例如,

    Character [] a = new Character[]{'a','b','c'};
    

    不要使用 char,因为它会在类型检查时编译错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2018-08-01
      • 2023-03-03
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多