Java集合框架Example-2

课程修改

public void testModify(){
		coursesToSelect.set(4,new Course("7","ITPS"));
		
	}
删除
/*
 * 删除List中的元素
 */
	public void testRemove(){
		Course cr=(Course) coursesToSelect.get(4);
		coursesToSelect.remove(cr);
		System.out.println("成功删除");
		testForEach();
	}
	
/*
 * 删除2
 */
	public void testRemove1(){
		System.out.println("即将删除序列为2的课程");
		coursesToSelect.remove(2);
		testForEach();
	}
	
/*<pre name="code" class="java">public class TestGeneric {

	/*
	* 带有泛型---Course的List类型属性
	*/
	public List<Course> courses;
	public TestGeneric(){
		this.courses=new ArrayList<Course>();//()意思是调用构造方法
	}
/*
 * 测试增加
 */
	public void testAdd(){
		Course cr1=new Course("1","English");
		courses.add(cr1);
		Course cr2=new Course("2","German");
		courses.add(cr2);
	}
/*
 * 测试循环遍历
 */
	public void testForEach(){
		for(Course cr:courses){
			System.out.println(cr.id+" "+cr.name);
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestGeneric Tg=new TestGeneric();
		Tg.testAdd();
		Tg.testForEach();
			
	}
/*
 * 删除4,5位上的元素
 */
<span style="white-space:pre">	</span>public void testRemoveAll(){
<span style="white-space:pre">		</span>System.out.println("即将删除序列为4,5的课程");
<span style="white-space:pre">		</span>Course[] courses={(Course) coursesToSelect.get(4),(Course) coursesToSelect.get(5)};
<span style="white-space:pre">		</span>coursesToSelect.removeAll(Arrays.asList(courses));
<span style="white-space:pre">		</span>System.out.println("成功删除课程");
<span style="white-space:pre">		</span>testForEach();
<span style="white-space:pre">	</span>}

 泛型 

集合中的元素可以是任意类型的对象(对象的引用)。如果把某个对象放入集合,则会忽略他的类型,而把他当作Object处理

泛型则是规定了某个集合只可以存放特定类型的对象,会在编译期间进行类型检查,可以直接按指定类型获取集合元素。

public class TestGeneric {

	/*
	* 带有泛型---Course的List类型属性
	*/
	public List<Course> courses;
	public TestGeneric(){
		this.courses=new ArrayList<Course>();//()意思是调用构造方法
	}
/*
 * 测试增加
 */
	public void testAdd(){
		Course cr1=new Course("1","English");
		courses.add(cr1);
		Course cr2=new Course("2","German");
		courses.add(cr2);
	}
/*
 * 测试循环遍历
 */
	public void testForEach(){
		for(Course cr:courses){
			System.out.println(cr.id+" "+cr.name);
		}
	}
	
	public static void main(String[] args) {
		TestGeneric Tg=new TestGeneric();
		Tg.testAdd();
		Tg.testForEach();
			
	}

泛型集合中除了能存入泛型类型还能存入泛型子类型。泛型集合中的限定类型不能使用基本数据类型,只能引用类型。可以通过使用包装类限定允许存入的基本类型数据。int-integer;long-Long; boolean-Boolean

/*
 * 基本类型包装类
 */
	public void testBasicType(){
		List<Integer> list=new ArrayList<Integer>();
		list.add(1);
		System.out.println("基本类型必须使用包装类"+list.get(0));
	}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值