Collection父接口
- 特点:代表一组任意类型的对象,无序,无下标,不能重复
- 方法:
- boolean add(Object obj)//添加一个对象
- boolean addAll(Collection c)//将一个集合中的所有对象添加到此集合中
- void clear()//清空此集合中的所有对象
- boolean contains(Object o)//检查此集合中是否包含o对象
- boolean equals(Object o)//比较此集合是否与指定对象相等
- boolean isEmpty()//判断此集合是否为空
- boolean remove(Object o)//在此集合中移除o对象
- int size()//返回此集合中的元素个数
- Object[] toArray()//将此集合转换成数组
示例代码如下
package com.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo01 {
public static void main(String[] args) {
Collection collection=new ArrayList();
collection.add("苹果");
collection.add("橘子");
collection.add("芒果");
System.out.println("元素个数"+collection.size());
System.out.println(collection);
System.out.println("删除之后"+collection.size());
System.out.println("==============================");
for (Object object:collection)
{
System.out.println(object);
}
System.out.println("==================================");
Iterator it =collection.iterator();
while(it.hasNext()){
String s =(String)it.next();
System.out.println(s);
}
System.out.println("元素个数"+collection.size());
System.out.println(collection.contains("苹果"));
System.out.println(collection.isEmpty());
}
}
package com.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo02 {
public static void main(String[] args) {
Collection collection=new ArrayList();
Student s1=new Student("张三",20);
Student s2=new Student("李四",21);
Student s3=new Student("王五",19);
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println("元素个数"+collection.size());
System.out.println(collection.toString());
System.out.println("================================");
for (Object object:collection)
{
Student s =(Student) object;
System.out.println(s.toString());
}
System.out.println("====================");
Iterator it = collection.iterator();
while(it.hasNext()){
Student s=(Student) it.next();
System.out.println(s.toString());
}
System.out.println(collection.contains(s1));
System.out.println(collection.isEmpty());
}
}
package com.collection;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
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 "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}