本帖最后由 littlefoxtail 于 2013-5-13 13:24 编辑
- import java.util.*;
- import java.util.Comparator;
- public class Noname1 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ////元素为People的ArrayList集合
- ArrayList<Person> al = new ArrayList<Person>();
- al.add(new Person("abc1"));
- al.add(new Person("abc2"));
- al.add(new Person("abc3"));
- Iterator<Person> it = al.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next().getName());
- }
- ArrayList<Student> al1 = new ArrayList<Student>();//元素为Student的ArrayList集合
- al1.add(new Student("abc--1"));
- al1.add(new Student("abc--2"));
- al1.add(new Student("abc--3"));
-
- Iterator<Student> it1 = al1.iterator();
- while(it1.hasNext())
- {
- System.out.println(it1.next().getName());
- }
-
- System.out.println(al.addAll(al1));//true
-
- Iterator<Person> it2= al.iterator();
- while(it2.hasNext())
- {
- System.out.println(it2.next().getName());
- /*打印abc1
- abc2
- abc3
- abc--1
- abc--2
- abc--3*/
- }
- System.out.println("-----");
- al.add(new Student("abc--4"));
-
- it2= al.iterator();
- while(it2.hasNext())
- {
- System.out.println(it2.next().getName());
- /*打印abc1
- abc2
- abc3
- abc--1
- abc--2
- abc--3
- abc--4*/
- }
- }
- }
- class Person{
- private String name;
- Person(String name){
- this.name=name;
- }
- public String getName(){
- return name;
- }
- }
- class Student extends Person{
- Student(String name){
- super(name);
- }
- }
- class Comp implements Comparator<Person>{
- public int compare(Person s1,Person s2){
- return s1.getName().compareTo(s2.getName());
- }
- }
复制代码 有两个问题想不太明白
第一个ArrayList已经指定类型为People
1.add方法可以add子类类型
2.addAll方法可以添加第二个ArrayList集合中所有Student元素
泛型中应该没有多态这一说吧 |