集合
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
和数组的区别:
- 数组长度固定,集合长度不固定
- 数组可以存储基本类型和引用类型,集合只能存储引用类型。
位置:java.util.*
特点:代表一组任意类型的对象,无序,无下标,不能重复。
collection方法
add();
remove();
Iterator();-----> hasNext(); next(); remove();
contains();
package com.zhang.oop.Coll;
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("zy");
collection.add("ch");
collection.add("rt");
System.out.println(collection);
//删除元素
collection.remove("ch");
System.out.println(collection);
//遍历元素
for (Object o : collection) {
System.out.println(o);
}
//用迭代器遍历元素
Iterator it = collection.iterator();
while (it.hasNext()){ //hasNext(); 有没有下一个元素
Object object = it.next(); //next(); 获取下一个元素
System.out.println(object);
//it.remove(); 不能使用collection的删除,会报异常
}
System.out.println(collection.size());
//判断是否存在这个元素
System.out.println(collection.contains("zy"));
}
}
collection 操作学生信息
package com.zhang.oop.Coll;
public class Students {
private String name;
private int age;
public Students(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;
}
}
package com.zhang.oop.Coll;
import com.zhang.oop.Obct.Student;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Application {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("张三",22);
Student s2 = new Student("李四",33);
Student s3 = new Student("王五",43);
//增加信息
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println(collection);
//删除信息
collection.remove(s1);
System.out.println(collection);
//遍历信息
for (Object o : collection) {
System.out.println(o);
}
//用迭代器遍历信息
Iterator it = collection.iterator();
while (it.hasNext()){
Object object = it.next();
System.out.println(object);
}
//判断是否存在这个信息
System.out.println(collection.contains(s2));
//判断是否为空
System.out.println(collection.isEmpty());
}
}
标签:name,System,collection,println,集合,public,out
From: https://www.cnblogs.com/rockz/p/17217548.html