}public class Exercise { public static void main(String[] args) throws IOException { //three ways to construct an Arraylist //capacity refers to the length of private member elementData which is Object[]
ArrayList<Person> a1=new ArrayList<Person>();//default initial capacity,size 0 ArrayList<Person> a2=new ArrayList<Person>(20);//make a array of length 20 for elementData,size=0
ArrayList<Man> a3=new ArrayList<Man>(l1);
这样就ok的
给Lz修改了一下,ArrayList要限定类型Man,想打印出来再复写一下toString方法import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;public class CollectionTest
{ public static void main(String[] args)
{
Collection<Man> l1=new LinkedList<Man>();
l1.add(new Man("Tom"));
l1.add(new Man("John"));
ArrayList<Man> a3=new ArrayList<Man>(l1);
for(Man m : a3)
{
System.out.println(m);
} }
}
class Person
{
String name;
}
class Man extends Person
{
Man(String name)
{
this.name=name;
}
public String toString()
{
return name.toString();
}
}
import java.io.IOException;
import java.util.*;class Person{
String name;
}class Man extends Person{
Man(String name){this.name=name;}
}public class Exercise
{
public static void main(String[] args) throws IOException {
//three ways to construct an Arraylist
//capacity refers to the length of private member elementData which is Object[]
ArrayList<Person> a1=new ArrayList<Person>();//default initial capacity,size 0
ArrayList<Person> a2=new ArrayList<Person>(20);//make a array of length 20 for elementData,size=0
Collection<Man> l1=new LinkedList<Man>();
l1.add(new Man("Tom"));
l1.add(new Man("John"));
ArrayList<Person> a3=new ArrayList<Person>(l1);
}
}
不是警告 编译错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor ArrayList<Man>(Collection<Man>) is undefined
Collection<Man> l1=new LinkedList<Man>();
ArrayList<Person> a3=new ArrayList<Person>(l1);类型转换有问题吧,Man转Person?