自己实现HashSet类和rrayList类

来源:互联网 发布:最近流行的网络歌手 编辑:程序博客网 时间:2024/06/06 00:13

自己实现了HashSet类和ArrayList类,只是简单的实现了它们的几个方法,写出的类限制性很大。使用JDK提供的类的时候,应该要知道他们的底层的细节是怎么实现的,对以后使用和加什么理解有一定的帮助。JDK文档提供一个方法介绍,没有提供底层实现的细节,也没有具体每个方法实现的简单示例。Add()方法动态添加元素我认为,如果申请的空间满了之后每次会再开辟一块如大小为16空间的来存储,而不是每次开辟大小为1的空间。这样实现了动态增长。

看代码:

自己写的HashSet类

public class MyHashSet {static int num = 0;static Object[] object;public MyHashSet()//无参数构造函数{object = new Object[16];}public MyHashSet(int number)//带参数构造函数{object = new Object[number];}private static void Add(Object E)//添加元素方法{if(object.length >= num){Object[] objectold = new Object[num];for(int i = 0; i < num; i++){objectold[i] = object[i];}object = new Object[num + 16];for(int i = 0; i < num; i++){object[i] = objectold[i];}}object[num++] = E;}private static boolean MyContains(Object E)//检查是否存在某个元素方法{for(int i =0; i < num; i++){if(object[i] == E) return true;}return false;}private static void ForEach()//遍历方法{for(int i = 0; i < num; i++){System.out.print(object[i] + " ");}System.out.println();}private int Size()//返回hashset的大小,即元素个数{return num;}public static void main(String[] args) {MyHashSet myhashset = new MyHashSet(10);//Add方法for(int i = 1; i<= 10; i++){MyHashSet.Add(i);}//遍历方法System.out.println("myhashset元素如下:");MyHashSet.ForEach();//元素个数方法int size = myhashset.Size();System.out.println("myhashset元素个数为" + size);//检查某个元素是否存在int checknum1 = 4;if(MyContains(checknum1) == true){System.out.println("myhashset中存在元素"+checknum1);}else{System.out.println("myhashset中不存在元素"+checknum1);}}}


自己写的ArrayList类:

public class MyArrayList {static int num = 0;static Object[] object;public MyArrayList(){    object = new Object[16];}public MyArrayList(int number){    object = new Object[number];}private void Add(Object E){if(object.length >= num){Object[] objectold = new Object[num];for(int i = 0; i < num; i++){objectold[i] = object[i];}object = new Object[num + 16];for(int i = 0; i < num; i++){object[i] = objectold[i];}}object[num++] = E;}private static boolean MyContain(Object E){for(int i = 0; i < num; i++){if(object[i] == E)return true;}return false;}private static void ForEach(){for(int i = 0; i < num; i++){System.out.print(object[i] + " ");}System.out.println();}private Object ReMove(Object E){int i = 0;while(object[i] != E) i++;for(;i < num; i++){object[i] = object[i+1];}num = num -1;return object;}public static void main(String[] args) {//声明MyArrayList myArrayList = new MyArrayList();//Add方法for(int i = 1; i < 10; i++){myArrayList.Add(i);}//遍历方法System.out.println("myArrayList元素如下:");myArrayList.ForEach();//检查某个元素是否存在int checknum1 = 4;if(MyContain(checknum1) == true){System.out.println("myArrayList中存在元素"+checknum1);}else{System.out.println("myArrayList中不存在元素"+checknum1);}//移除一个元素1int checknum2 = 1;myArrayList.ReMove(checknum2);System.out.println("移除元素"+checknum2+"后:");myArrayList.ForEach();}}