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));
}
}
}
以上代码实现了一个简单的集合对象,有助于大家理解泛型的使用。所以,理解好这个程序,能对泛型的理解更加的深刻。利用泛型自己定义一个简单的集合
最新推荐文章于 2021-04-11 15:38:53 发布
