Arraylist implementation
Similar question:
- dynamic array implementation
- custom arraylist implementation
- own arraylist implementation
- class MyArray<E> {
- static int length = 0;
- static int capacity = 10;
- static Object arr[];
- MyArray(){
- arr = new Object[capacity];
- }
- public void add(E value) {
- if (capacity == length) {
- increaseCapacity();
- }
- arr[length] = value;
- length++;
- }
- public static void increaseCapacity() {
- capacity=capacity*2;
- arr=Arrays.copyOf(arr, capacity);
- }
- public static int size() {
- return length;
- }
- public E get(int index) {
- if(index>length){
- throw new ArrayIndexOutOfBoundsException();
- }
- else return (E) arr[index];
- }
- public boolean contain(E value) {
- for(int i=0;i<length;i++){
- if(arr[i]==value)
- return true;
- }
- return false;
- }
- }
Test
- public class Array1 {
- public static void main(String[] args) {
- MyArray m2=new MyArray();
- m2.add(1);
- m2.add("2");
- for (int i = 0; i < m2.length; i++) {
- System.out.println(m2.get(i));
- }
- }
- }
Comments
Post a Comment