Collection使用(1)
package com.etc.chen;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
* Collection接口使用
* (1)添加元素
* (2)删除元素
* (3)遍历元素
* (4)判断
* */
public class Demo01 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
// (1)添加元素
collection.add("香蕉");
collection.add("苹果");
collection.add("榴莲");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
// (2)删除元素
// collection.remove("榴莲");
// collection.clear();
// System.out.println("删除之后:"+collection.size());
// (3)遍历元素
// 3.1使用增强for
System.out.println("使用增强for------------------------");
for (Object object:collection
) {
System.out.println(object);
}
//3.2使用迭代器(迭代器专门用来遍历及格的一种方式)
//hasNext();有没有下一个元素
//next();获取下一个元素
//remove();删除当前元素
System.out.println("使用迭代器--------------------------");
Iterator it = collection.iterator();
while (it.hasNext()){
String s = (String) it.next();
System.out.println(s);
//it.remove();
}
// (4)判断
System.out.println(collection.contains("香蕉"));
System.out.println(collection.isEmpty());
}
}
Collection使用(2)
package com.etc.chen;
public class Student {
private String name;
private int age;
public Student() {
}
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 +
'}';
}
}
package com.etc.chen;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo02 {
public static void main(String[] args) {
//新建Collection对象
Collection collection = new ArrayList();
Student s1 = new Student("chen",20);
Student s2 = new Student("ma",20);
Student s3 = new Student("陈",21);
//1.添加学生
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println(collection.size());
System.out.println(collection.toString());
//2.删除
//collection.remove(s1);
//System.out.println(collection.size());
System.out.println("-------------------------------------");
//3.遍历
for (Object object:collection
) {
Student s = (Student) object;
System.out.println(s.toString());
}
System.out.println("--------------------------------------");
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.println(student.toString());
}
//4.判断
System.out.println(collection.contains(new Student("ccc",22)));
System.out.println(collection.contains(s1));
System.out.println(collection.isEmpty());
}
}