如果有多个类,而且他们其中有一些方法是相同的,我是选择在每个类中都把这些方法实现一遍呢,还是选择泛型。我今天自己花了一点时间看了看泛型,实践了一下。
Holder.java
package regexp; import java.util.Collection; import java.util.Iterator; import java.util.Set; public class Holder<T> { private T a; public Holder(T a) { this.a = a;} public void set(T a) { this.a = a;} public T get() { return a;} public static void main(String[] args) { Holder<A> h1 = new Holder<A>(new A()); A a = h1.get(); a.id = a.score = 1; Holder<B> h2 = new Holder<B>(new B()); B b = h2.get(); b.id = 2; b.name = "2"; System.out.printf("A: id = %d , score = %d ; B: id = %d , name = %s%n",a.id,a.score,b.id,b.name); } } class A { public A() { } int id; int score; } class B { public B() { } int id; String name; }
如果要对这些类做一些操作,比如说要把他们的对象排个序什么的。那咱可以把上述代码改成下面这样:
package regexp; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; public class Holder<T> { private T a; public Holder(T a) { this.a = a;} public void set(T a) { this.a = a;} public T get() { return a;} public static void main(String[] args) { List<A> la = new LinkedList<A>(); Holder<A> h1 = new Holder<A>(new A()); A a = h1.get(); a.id = a.score = 1; la.add(a); a.id = a.score = 2; la.add(a); List<B> lb = new LinkedList<B>(); Holder<B> h2 = new Holder<B>(new B()); B b = h2.get(); b.id = 2; b.name = "2"; lb.add(b); b.id = 3; b.name = "3"; lb.add(b); //自定义比较器 Collections.sort(la,new Comparator<A>() { public int compare(A a,A b) { if(a.id != b.id) { return a.id - b.id; } else { return a.score - b.score; } } });//这里只是举了个例子对la操作了一下 System.out.printf("A: id = %d , score = %d ; B: id = %d , name = %s%n",a.id,a.score,b.id,b.name); } } class A { public A() { } int id; int score; } class B { public B() { } int id; String name; }
如果还需要对A,B实现更多的操作,如果这些操作是他们俩所共有的,那么就在泛型中编写;如果是各自所具有的,那么就在他们各自的类中实现即可。