package test.com.atguigu.javase.lesson8;
import com.atguigu.javase.lesson8.Person;
import org.junit.Test;
import java.util.*;
/**
* GenericTest Tester.
*/
public class GenericTestTest {
/**
* 不使用泛型时:
* 1.集合中的类型并不安全,可以向集合中放入任何引用类型的对象
* 2.从集合中取出的对象都是Object类型,在具体操作时,可能需要类型的强制转换。
* 那么在强制类型转换时也容易发生ClassCastException。
*/
@Test
public void helloGeneratic(){
List persons = new ArrayList();
persons.add(new Person("AA",12));
persons.add(new Person("BB",13));
persons.add(new Person("CC",14));
persons.add(new Person("DD",15));
persons.add(new Person("EE",16));
//persons.add("ABC");
for(int i = 0; i < persons.size(); i++){
Object obj = persons.get(i);
Person person = (Person)obj;
System.out.println(person);
}
System.out.println("----------");
List<Person> persons2 = new ArrayList();
persons2.add(new Person("AA",12));
persons2.add(new Person("BB",13));
persons2.add(new Person("CC",14));
persons2.add(new Person("DD",15));
persons2.add(new Person("EE",16));
//persons2.add("");//报错
System.out.println(persons2);
}
@Test
public void testCollectionsWithGeneratic(){
Set<Person> persons = new TreeSet<Person>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
persons.add(new Person("AA",12));
persons.add(new Person("BB",13));
persons.add(new Person("CC",14));
persons.add(new Person("DD",15));
persons.add(new Person("EE",16));
Iterator<Person> iterator = persons.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
泛型
最新推荐文章于 2023-11-27 08:52:01 发布