Java: Using one Method for different types in the array parameter
I just can开发者_如何学运维t't figure this out maybe you can help me.
The problem:
public class class1 implements Comparable<class1> {
public int compareTo(class1 o) {
//some code
}
}
public class class2 implements Comparable<class2> {
public int compareTo(class2 o) {
//some code
}
}
public class foo {
private ArrayList<Class1> abc = new ArrayList<Class1>();
private ArrayList<Class2> def = new ArrayList<Class2>();
}
In the following o = abc or def
public int foo1 (ArrayList<Object> o) {
o[0].compareTo(o[1]);
}
This code keeps getting me this error:
The method compareTo(class1) is undefined for the type Object
I do understand why but I can't find a workarround so that I don't have to duplicate code, which would be necessary because I have more ArrayList objects and much longer code.
I hope one of you has an idea.
PROBLEM SOLVED!!! Solution was :
public <T extends Comparable<T>> int foo1 (ArrayList<T> o) {
return o.get(0).compareTo(o.get(1));
}
by Peter Lawrey
When you use an object by it's super class methods, you cannot assume that it's subclass methods are available.
try the following which compiles and works for abc
and def
without warning.
public <T extends Comparable<T>> int foo1 (ArrayList<T> o) {
return o.get(0).compareTo(o.get(1));
}
implements Comparable<class1>
you are implementing so you need to provide implementation for all the method of interface otherwise make it abstract
implement it like
public class class1 implements Comparable<class1> {
public int compareTo(class1 o) {
//some code
}
}
public class class2 implements Comparable<class2> {
public int compareTo(class2 o) {
//some code
}
}
- Interface Doc
You need to make the method generic:
public <T extends Comparable<? super T>> int foo1 (ArrayList<T> o) {
精彩评论