Java中Collection集合

120 阅读1分钟

Collection<E>集合是个接口,故不能实例化,但是它的子类可以实例化

集合的继承关系:

Collection
List
ArrayList
Vector
LinkedList
Set
HashSet
TreeSet

List集合blog.csdn.net/HeZhiYing_/…

Set集合blog.csdn.net/HeZhiYing_/…

ArrayLIst实现了Collection接口,以字符串举例:

import java.util.ArrayList;
import java.util.Collection;

public class Main {
	public static void main(String[] args) {
		/*
		 * 用Collection集合存储字符串,并且遍历
		 */
		Collection<String> c = new ArrayList<String>();//此处的<>是泛型的意思
		c.add("hello");
		c.add("world");
		c.add("java");
		c.add("hello");

		for (String s : c) {//便利该集合
			System.out.println(s);
		}
	}
}

运行结果是:

 以学生类举例:

import java.util.ArrayList;

import java.util.Collection;

/*
 * 定义了一个学生类
 */
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 this.name;
	}
	
	public int getAge() {
		return this.age;
	}

}

public class Main {
	public static void main(String[] args) {
		/*
		 * 用Collection集合存储学生类,并且遍历
		 */
		Collection<Student> c = new ArrayList<Student>();// 此处的<>是泛型的意思
		Student s1 = new Student("贺志营", 22);
		Student s2 = new Student("杨洋", 26);
		
		c.add(s1);
		c.add(s2);
		
		for(Student s : c) {
			System.out.println(s.getName()+"---"+s.getAge());
		}
	}
}

运行结果: