泛型: 可以把类型当作参数一样传递过来, 在传递过来之前我不明确,
但是在使用的时候我就用明确了。
(早期的 Object 类型可以接收任意的对象类型, 但是在实际的使用中, 会有类型转换的问题。)
也就存在这隐患, 所以 Java 提供了泛型来解决这个安全问题。
泛型通配符《?》 (<>)
任意类型, 如果没有明确, 那么就是 Object 以及任意的 Java 类了
? extends E
向上限定, E 及其子类
? super E
向下限定, E 及其父类
eg:类 ArrayList《E》(是<>)
ArrayList《Student》 s = new ArrayList《Student》(); (是<>)
遍历:
for(Student ss : s){
System.out.println(ss.getName()+"---"+ss.getAge());
}
Iterator<Student> si = s.iterator();
while(si.hasNext()){
Student stu = si.next();
System.out.println(stu.getName()+"---"+stu.getAge());
}
for(int i =0;i<s.size();i++){
Student stu = s.get(i);
System.out.println(stu.getName()+"---"+stu.getAge());
}
类 HashMap《K,V》(是<>)
Map<Student, String> s = new HashMap<Student, String>();
s.put(new Student("黄", 20),"1");
s.put(new Student("拉面", 20),"2");
s.put(new Student("蓝", 20),"3");
for(Student stu : s.keySet()){
String ss = s.get(stu);
System.out.println(stu + " " + ss);
}
for(String s1 : s.values()){
System.out.println(s1);
}
TreeMap(Comparator《? super K》 comparator) (<>)
TreeSet用comparator构造的两种方法
public class TreeSetTest {
// public static void main(String[] args) {
// TreeSet<Student> s = new TreeSet<Student>(new Comparator<Student>(){
//
// @Override
// public int compare(Student o1, Student o2) {
// int result = o2.getName().length() - o1.getName().length();
// result = result == 0 ? o2.getAge() - o1.getAge() : result;
// return result;
// }
// });
//
// s.add(new Student("小黄",44));
// s.add(new Student("小绿lv ",55));
// s.add(new Student("小绿",56));
// for(Student ts:s){
// System.out.println(ts);
// }
// }
//}
public static void main(String[] args) {
TreeSet<Student> s = new TreeSet<Student>(new MyComparator());
s.add(new Student("小黄", 44));
s.add(new Student("小绿", 55));
s.add(new Student("小绿", 56));
for (Student ts : s) {
System.out.println(ts);
}
}
}
class MyComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
int result = o1.getName().length() -o2.getName().length();
result = result == 0 ? o1.getAge() - o2.getAge() : result ;
return result;
}
}