利用泛型自己定义一个简单的集合

本文介绍了一个使用Java泛型实现的简易集合类,通过具体示例代码展示了泛型的基本用法,包括如何定义泛型类、添加和获取元素、删除指定位置的元素等操作。
package com.fanxing; 


/** 
 * @author 鲁志明  E-mail: 13688601037@139.com
 * @version 创建时间:2013-6-1 下午4:34:41 
 * 
 */
public class SimpleCollection<Type> {

	private Type[] objArray;
	private int index = 0 ; 
	public SimpleCollection()
	{
		objArray = (Type[])new Object[10];
	}
	
	public void add(Type type)
	{
		objArray[index] = type;
		index++;
	}
	public Type get(int index)
	{
		return objArray[index];
	}
	public int size()
	{
		return index;
	}
	public void remove(int index)
	{
		if(index > this.index)
		{
			System.out.println("没有这个元素,无法删除");
			return;
			
		}
		//如果删除的是最后一个元素
		if(this.index == index)
		{
			objArray[index] = null;
			this.index--;
			return;
		}
		//如果删除的是中间的某个元素或者第一个元素
		else
		{
			
			for(int i = 0 ; i< this.index-index; i++)
			{
				objArray[index+i] = objArray[index+i+1];
				
			}
			this.index -- ;
		}
	}
	
	public static void main(String[] args) {
		SimpleCollection<Integer> sc = new SimpleCollection<Integer>();
		sc.add(1);
		sc.add(2);
		sc.add(3);
		sc.add(4);
		for(int i = 0 ; i< sc.size() ; i++)
		{
			System.out.println(sc.get(i));
		}
		
		sc.remove(2);
		System.out.println("=====================");
		for(int i = 0 ; i< sc.size() ; i++)
		{
			System.out.println(sc.get(i));
		}
	}
}

以上代码实现了一个简单的集合对象,有助于大家理解泛型的使用。所以,理解好这个程序,能对泛型的理解更加的深刻。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值