为了练习下策略模式,所以想实现自己的一个可重复带排序(正序,倒序)的List,在客户端调用环境角色的sort方法时,出现了错误,请大家帮忙分析下...
package java20130302;
import java.util.Iterator;
public class Client {
public static void main(String[] args) {
SortStg ps = new PositiveSort();
SortStg rs = new ReverseSort();
MyList<Person> list = new MyList<Person>(ps);
Person p1 = new Person("bb", 22, 1001);
Person p2 = new Person("dd", 21, 1006);
Person p3 = new Person("aa", 20, 1004);
Person p4 = new Person("cc", 22, 1003);
Person p5 = new Person("gg", 21, 1005);
Person p6 = new Person("ee", 23, 1002);
Person p7 = new Person("ff", 24, 1008);
Person p8 = new Person("aa", 19, 1007);
Person p9 = new Person("aa", 20, 1007);
Person p10 = new Person("ii", 26, 1007);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
list.add(p6);
list.add(p7);
list.add(p8);
list.add(p9);
list.add(p10);
System.out.println("原list: ");
for (Iterator<Person> iterator = list.iterator(); iterator.hasNext();) {
Person person = (Person) iterator.next();
System.out.println(person);
}
list.sort();
System.out.println("升序排序后: ");
for (Iterator<Person> iterator = list.iterator(); iterator.hasNext();) {
Person person = (Person) iterator.next();
System.out.println(person);
}
list.setS(rs);
list.sort();
System.out.println("降序排序后:");
for (Iterator<Person> iterator = list.iterator(); iterator.hasNext();) {
Person person = (Person) iterator.next();
System.out.println(person);
}
}
}
package java20130302;
public interface SortStg {
public void sort(MyList<Person> myList);
}
package java20130302;
import java.util.ArrayList;
@SuppressWarnings("hiding")
public class MyList<Person> extends ArrayList<Person> {
/**
*
*/
private static final long serialVersionUID = 1L;
private SortStg s;
public MyList(SortStg s) {
this.s = s;
}
public void setS(SortStg s) {
this.s = s;
}
@SuppressWarnings("unchecked")
public void sort() {
s.sort((MyList<java20130302.Person>) this);// 问题就出现在这里,为什么要强制转换后才正确
//原来是这样的s.sort(this);出现错误:The method sort(MyList<Person>) in the type SortStg is not applicable for the arguments (MyList<Person>)
}
}
------解决方案--------------------
就是 这个问题,this 是在运行期才确定是什么类型,编译期间是不知道的,所以要现转换告诉编译器什么类型.