【发布时间】: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);
简而言之,哪种做事方式更好以及出于什么原因——如果两者都有值得了解的成本和收益,那么请同时说明这些原因。 谢谢
【问题讨论】:
-
不,我的意思是超载。例如,beginnersbook.com/2013/05/method-overloading
标签: java casting operator-overloading