Java基础__Java中集合类 传送门
自定义MyArrayList集合实现:增加数据、取数据、查看集合中数据个数方法
package com.Gary; public class MyArrayList { private int[] dataArray = new int[100]; private int index = 0; public void add(int data) {
dataArray[index] = data;
index++;
} public int get(int index) {
if(index >=0 && index<=(this.index-1) )
{
return dataArray[index];
}else {
System.out.println("无数据");
return -1;
}
} public int size() { return index;
} }
MyArrayList.java
package com.Gary; public class Test {
public static void main(String[] args) {
MyArrayList list = new MyArrayList(); //添加数据
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5); //输出数据
//System.out.println(list.get(1));
//System.out.println(list.get(10)); System.out.println(list.size()); for(int i=0;i<list.size();i++)
{
System.out.println("输出list中的数据:"+list.get(i));
} }
}
Test.java
为了适应任意类型的数据,可以将我们自定义的集合类定义为泛型MyArrayList<T>
package com.Gary; public class Test {
public static void main(String[] args) {
//MyArrayList<String> 字符类型
MyArrayList<Integer> list = new MyArrayList<Integer>(); list.add(1);
list.add(2); for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
} }
}
Test.java
package com.Gary; public class MyArrayList<T> { private T[] dataArray = (T[]) new Object[100]; private int index = 0; public void add(T data) {
dataArray[index] = data;
index++;
} public T get(int index) {
if(index >=0 && index<=(this.index-1) )
{
return dataArray[index];
}else {
System.out.println("无数据");
return null;
}
} public int size() { return index;
} }
MyArrayList.java