数组,ArrayList,HashSet的用法及注意点。

数组的用法:初始化及赋值:

1.int[] a=new int[3];

a[0]=1;

a[1]=2;

a[2]=3;

2.int[] a={1,2,3};

3.Date[] dates=new Date[2];

dates[0]=new Date(2012, 3, 13));

dates[1]=new Date(2013, 3, 13));

dates[2]=new Date(2014, 3, 13));

4.Date[] dates={new Date(2009,10,26),new Date(2010,10,26),new Date(2011,10,26)};

数组的长度的用法为:a.length;

ArrayList用法及其注意点:

ArrayList<Interger> list=new ArrayList<Interger>();

list.add(1);//ArrayList是有序的。加入1进入ArrayList,添加到当前ArrayList的最后一位。

list.add(1);//这里注意下,ArrayList因为有次序,所以可以连续添加相同元素,这点与HashSet是不同的。

list.add(3);

//list.remove(Interger i);//除元素i;

//list.remove(index i);//移除下标为i的元素; list.remove((Integer) 3);//这里要注意,如果想要移除元素3,则要加Interger。不然的话,因为remove有两种方法,它会自动变为index,容易造成越界,报错。如果想要移除下标为3的元素,则不用加。

ArrayList的长度用法为list.size(),这里值为3;

HashSet用法及其注意点:

HashSet<Integer> hash=new HashSet<Integer>();

hash.add(1);//HashSet是无序的。

hash.add(1);//HashSet因为是无序的,所以添加相同元素是不允许的,这方法内部会判断是否存在相同的元素,如果已存在相同元素,则hash保持不变。

hash.add(3);

HashSet的长度为hash.size(),这里值为2;

经验分享 程序员 微信小程序 职场和发展