【问题标题】:Is it better practice to cast or to use overloaded methods?强制转换或使用重载方法是更好的做法吗?
【发布时间】:2014-12-17 07:10:07
【问题描述】:

更新 这个问题不太关心改进以下示例代码的最有效方法,因为它是关于为什么转换(或不)优先于使用重载方法的根本原因(以及在什么情况下)。因此,在上述范围内的答案将是最大的帮助。谢谢。

我有一个关于使用重载方法与强制转换的一般“最佳实践”问题,并且想知道哪个被认为“更好”以及为什么。

比如说,我有两种不同类型的对象,例如 Animal-Object 和一个 Computer-Object,我希望通过两种完全相同的方法将它们添加到原始数组(而不是 ArrayList)中除了他们的类型之外的每一个方面。在这种情况下,是否认为在重载方法方法中创建两个具有相同名称的单独方法(每种类型一个)更好,或者创建由“对象”对象组成的单个方法然后进行转换会更明智以后变成想要的类型?

选项一(未经测试的代码)

public Animal[] updateArray(Animal name, Animal[] animalArray){
    Animal[] updatedArray = null;

    if(animalArray==null){
        updatedArray = new String[1];
        updatedArray[0] = name; 
    }else{
        updatedArray = new Animal[animalArray.length +1];
        for(int i = 0; i<animalArray.length;i++){
            updatedArray[i] = animalArray[i];
        }
        updatedArray[updatedArray.length-1] = name;
    }
    return updatedArray;
}

和...

public Computer[] updateArray(Computer name, Computer[] computerArray){
        Computer[] updatedArray = null;

        if(computerArray==null){
            updatedArray = new String[1];
            updatedArray[0] = name; 
        }else{
            updatedArray = new Computer[computerArray.length +1];
            for(int i = 0; i<computerArray.length;i++){
                updatedArray[i] = computerArray[i];
            }
            updatedArray[updatedArray.length-1] = name;
        }
        return updatedArray;
}

选项二:使用更通用的做事方式并转换为正确的类型... (未经测试的代码)

public Object[] updateArray(Object name, Object[] computerArray){
        Object[] updatedArray = null;

        if(computerArray==null){
            updatedArray = new String[1];
            updatedArray[0] = name; 
        }else{
            updatedArray = new Computer[computerArray.length +1];
            for(int i = 0; i<computerArray.length;i++){
                updatedArray[i] = computerArray[i];
            }
            updatedArray[updatedArray.length-1] = name;
        }
        return updatedArray;
}

并用于某种方法,例如...

Animal[] animalArray = (Animal[]) updateArray(name, array); 
Computer[] computerArray = (Computer[]) updateArray(name, array); 

简而言之,哪种做事方式更好以及出于什么原因——如果两者都有值得了解的成本和收益,那么请同时说明这些原因。 谢谢

【问题讨论】:

标签: java casting operator-overloading


【解决方案1】:

最好的方法是使用泛型方法:

static<T> T[] updateArray(T t, T[] ary) {
    T[] result = Arrays.copyOf(ary, ary.length+1);
    result[ary.length] = t;
    return result;
}

不幸的是,数组和泛型不能很好地混合,并且存在各种陷阱。例如,像在代码中那样检查数组是否为空并创建一个新数组会变得很麻烦。这就是为什么我们有ArrayList——数组处理的蝙蝠侠。它弄脏了手,所以我们不必这样做。

【讨论】:

  • Misha,我非常感谢您对上述具体示例的建议,但是,我的问题的更大目标是了解何时以及为什么强制转换优于使用重载方法,您对此有何建议?也不是 ArrayList,不是原始数据类型等等,几乎都做与上面完全相同的事情吗?为什么这会被认为是“毛茸茸的”,我想这就是我要问的。谢谢
猜你喜欢
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
相关资源
最近更新 更多