UPDATE 这个问题与改进以下示例代码的最有效方法不太相关,因为它是关于为什么转换优于(或不优于)使用重载方法的根本原因(以及在什么情况下)。因此,属于上述范围的答案将是最大的帮助。谢谢。
我有一个关于使用重载方法与转换的一般“最佳实践”问题,我想知道哪个被认为“更好”以及为什么。
例如,我有两种不同类型的对象,例如 Animal-Object 和 Computer-Object,我希望通过两种完全相同的方法将它们添加到基本数组(而不是 ArrayList)中除了他们的类型之外的每一个方面。在这种情况下,是否认为以重载方法方法创建两个具有相同名称(每种类型一个)的单独方法更好,或者创建一个由“Object”对象组成的方法然后进行转换是否更明智?稍后转换成所需的类型?
选项一(未经测试的代码)
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);
简而言之,哪种做事方式更好,原因是什么——如果两者都有值得了解的成本和 yield ,那么也请说明这些原因。 谢谢
最佳答案
最好的方法是使用泛型方法:
static<T> T[] updateArray(T t, T[] ary) {
T[] result = Arrays.copyOf(ary, ary.length+1);
result[ary.length] = t;
return result;
}
不幸的是,数组和泛型不能很好地混合,并且存在各种陷阱。例如,检查数组是否为 null 并像在代码中那样创建一个新数组就变得很棘手。这就是为什么我们有 ArrayList
—— 数组处理的 bat 侠。它会弄脏自己的手,所以我们不必这样做。
关于java - 转换或使用重载方法是更好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27520046/