Java中有着许多数组,但是也分别动态数组与静态数组,ArrayList 就是其中一个动态数组,下面就让我们来看看它有哪些概念及如何使用吧。
一、ArrayList 是什么?
ArrayList集合:又名动态数组,可以容纳任意长度,任意类型的对象(不包括基本类型)List是有序的集合,所以和父接口Collection相比,多的是带下标的操作,它实现了Collection和List接口,能够灵活的设置数组的大小,它还能动态的增加和减少元素。
二、ArrayList 要怎么使用?
例1:package Collection;
//自己实现ArrayList to help understand unearneath
public class TestList
{
//核心就是数组
private Object[] elementData;
//数组的长度
private int size;
//空构造类
public TestList()
{
this(10);
}
//带参数的构造类.
public TestList(int initialCapacity)
{
//容量不能小于零
if (initialCapacity
{
try
{
throw new Exception();
}
catch (Exception e)
{
e.printStackTrace();
}
}
elementData = new Object[initialCapacity];
}
//主要的方法ADD方法 。
public boolean add(Object o)
{
//数组扩容当这个size超过数组的长度就扩容
if (size + 1 > elementData.length)
{
//你以为事将数组扩大,实际事换一个地方存放
Object[] newArray = new Object[size * 2 + 1];
//将数据拷贝到新数组
for (int i = 0; i
{
newArray[i] = elementData[i];
}
elementData = newArray;
}
//此时size进行了扩张
elementData[size++] = o;
return true;
}
//。size方法.
public int size()
{
return elementData.length;
}
//是否为空
public boolean isEmpty()
{
boolean f = false;
if (size == 0) f = true;
return f;
}
//获取对象
public Object get(int index)
{
//下标要进行判断
if (index = size)
{
try
{
throw new Exception();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Object o = elementData[index];
return o;
}
//
public void remove(int index)
{
//下标要进行判断
if (index = size)
{
try
{
throw new Exception();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//进行判断。删除以后要将后面的迁移 。
//这个是后面有的多少个元素个数
int numMoved = size - index - 1;
//将后面的元素往前一个覆盖。都不用删除。
if (numMoved > 0)
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
//删除指定对象
elementData[--size] = null;
}
//删除一个指定对象的
public void remove(Object index)
{
for (int i = 0; i
{
//循环进行比较用EQUALSE判断.
}
}
public static void main(String args[])
{
//first ,depends arrylist.we need to create a number
//of array
//
TestList list = new TestList();
list.add("3");
list.add("3");
list.remove(1);
System.out.println("数组有多少元素:" + list.size);
System.out.println("数组有多少大:" + list.size());
System.out.println("数组是否为空:" + list.isEmpty());
//System.out.println("数组是否为空:"+list.get(1));
}
}
例2:ArrayList List = new ArrayList();
List.Add(“string”);
List.Add(1);
//往数组中添加不同类型的元素
object[] values = List.ToArray(typeof (object)); //正确
string[] values = (string[]) List.ToArray(typeof (string)); //错误
例3:ArrayList List = new ArrayList();
for (int i = 0; i
List.Add(i);
//..程序做一些处理
List.RemoveAt(5); //将第6个元素移除
for (int i = 0; i
List.Add(i + 20);
Int32[] values = (Int32[]) List.ToArray(typeof (Int32)); //返回ArrayList包含的数组
以上就是关于ArrayList的所有内容了,如若还需要了解更多相关java入门知识,就快来关注奇Q工具网吧。
推荐阅读: