`
王的篇章
  • 浏览: 2819 次
  • 性别: Icon_minigender_1
  • 来自: 江西玉山
最近访客 更多访客>>
社区版块
存档分类
最新评论

JavaSE:类集之Collection

阅读更多

示例代码一:

 

package com.wbf.test;
import java.util.*;

class Person{
	private String name;
	private int age;
	
	public Person(){}
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "姓名: " + this.name + ", 年龄: " + this.age;
	}
}

public class CollectionDemo01 {
	public static void main(String[] args) {
		Collection c = new ArrayList();//父类引用指向子类对象
		//放入不同类型的对象
		c.add("hello");
		c.add(new Person("wbf", 20));
		c.add(new Integer(100));
		System.out.println(c.size());
		System.out.println(c);	
	}
}

 

解释说明:

 

 

  1. Collection c = new ArrayList();//父类引用指向子类对象,而没有使用ArrayList c = new ArrayList(), 更加灵活。当你不想用ArrayList换成LinkedList时,可以很方便的修改,对于下面所使用到的集合方法都不用变更,因为都是Collection接口提供的方法,没有使用子类特有的方法

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics