2012-01-11 71 views
2

有没有办法来重写一个Java方法,唯一改变的是一个ArrayList?覆盖在Java

例如:

public void quickSortMethod(ArrayList<Integer> comparison, int start, int end) 
{} 

public void quickSortMethod(ArrayList<Double> comparison, int start, int end) 
{} 

目前这使我有以下错误:

Method quickSortMethod(ArrayList<Integer>, int, int) has the same erasure quickSortMethod(ArrayList<E>, int, int) as another method in type QuickSort 

顺便说一句,我用我的参数中的ArrayList创建的其他对象

ArrayList<MyObject>...  

回答

3

不幸的是,没有。由于编译后的type erasure,两者没有区别。

+0

我是否必须创建两个方法(使用不同的名称),它们中唯一改变的是参数?任何建议? – 2012-01-11 02:58:00

+0

你可以走那条路,是的。你用这个'ArrayList'在这个方法里面做什么? – 2012-01-11 02:59:22

+0

如果我有ArrayList ,MyObject有很多变量,其中一个是数字(双精度)。我想根据该变量对ArrayList进行排序。问题是:我有MyObject2和MyObject3,它们与MyObject不同,但我也想对它们进行排序。 – 2012-01-11 03:05:28

9

在这种情况下,你可以尝试制作方法本身仿制并使用类型为ArrayList的类型......

public <T> void quickSortMethod(ArrayList<T> comparison, int start, int end) 
0

你可以做的是为一个函数

ArrayList<Object>,int,int 

,然后基于arraylist的对象类型使用不同的分析

0

由于您将使用这些数组列表作为参数对象,您可以定义自己的自定义对象,来自Arraylist的rit。这样,编译器会将您的重载识别为具有不同的签名。

当然,这意味着任何客户端代码都需要知道要传递哪个子类型。但是,这应该是一个相对容易解决的问题,因为如果你知道你正在提供参数对象int,然后初始化一个integerParamList。同样的双打。

不知道更多关于其他代码的信息,这可能是也可能不是合适的解决方案,但它可能会接近? (我不能对此进行测试,所以有可能是未知的问题。)

public class mySortingClass { 

    public void quickSortMethod(IntegerParamList comparison, int start, int end)  
    {}  

    public void quickSortMethod(DoubleParameterList comparison, int start, int end)  
    {} 

} 

public class IntegerParamList extends ArrayList<Integer> 
     {} 

public class DoubleParameterList extends ArrayList<Integer> 
     {} 
1

这是压倒一切的一个有效的例子,这里是 的也回答我们可以覆盖静态方法? 答案是否定的。

这里是示例代码。

package com.sample.test; 

类动物{

public static void showMessage() { 
    System.out.println("we are in Animal class"); 
} 

}

类狗延伸动物{

public void DogShow() { 
    System.out.println("we are in Dog show class"); 
} 

public static void showMessage() { 
    System.out.println("we are in static overridden method of dog class"); 
} 

}

类猫延伸动物{

public static void showMessage(){ 
    System.out.println("we are in overridden cat class"); 
} 

}

公共类AnimalTest {

public static void main(String[] args) { 
    Animal animal = new Animal(); 
    animal.showMessage(); 

    Dog dog = new Dog(); 
    dog.showMessage(); 

    Animal animal2 = new Dog(); 
    animal2.showMessage(); 

    Animal animal3 = new Cat(); 
    animal3.showMessage(); 

} 

}

OUTPUT:

我们在动物类 我们在狗类的静态覆盖的方法 我们在动物类 我们在动物类