Collection
可以存储多个数据,而且长度可以改变的容器。
Collection<E>是集合的顶级接口。
<E>---泛型
用于指定我们集合中元素的类型
由于泛型的指定集合中元素类型只能是引用数据类型
集合只能存储对象
Collection collection = new ArrayList();
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
System.out.println("元素个数"+collection.size());
System.out.println(collection);
collection.remove("榴莲");
System.out.println(collection);
collection.clear();
System.out.println("元素个数"+collection.size());
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
for (Object object : collection) {
System.out.println(object);
}
Iterator it = collection.iterator();
while(it.hasNext()) {
String object = (String)it.next();
System.out.println(object);
}
System.out.println(collection.contains("西瓜"));
System.out.println(collection.contains("枣子"));
System.out.println(collection.isEmpty());
Collection collection = new ArrayList();
StudentDemo stu1 = new StudentDemo("张三",16);
StudentDemo stu2 = new StudentDemo("张四",15);
StudentDemo stu3 = new StudentDemo("张五",17);
collection.add(stu1);
collection.add(stu2);
collection.add(stu3);
System.out.println(collection.size());
System.out.println(collection.toString());
collection.remove(stu1);
System.out.println(collection.size());
public class StudentDemo {
private String name;
private int age;
public StudentDemo(){
}
public StudentDemo(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "StudentDemo [name=" + name + ", age=" + age + "]";
}
}
List list = new ArrayList();
list.add("苹果");
list.add("小米");
list.add(0,"华为");
System.out.println(list.size());
System.out.println(list.toString());
list.remove(0);
System.out.println(list.size());
System.out.println(list.toString());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
for (Object object:list) {
System.out.println(object);
}
Iterator it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("--------列表迭代器---------");
System.out.println("--------列表迭代器-从前往后--------");
ListIterator it2 = list.listIterator();
while(it2.hasNext()) {
System.out.print(it2.nextIndex());
System.out.println(it2.next());
}
System.out.println("--------列表迭代器-从后往前--------");
while(it2.hasPrevious()) {
System.out.print(it2.previousIndex());
System.out.println(it2.previous());
}
System.out.println(list.indexOf("小米"));
System.out.println(list.subList(0, 1));