In this tutorial, I am giving an example implementation of List in java. Feel free to customize the behavior of list, by adding or removing methods from DemoList
class. If you have some ideas to make this implementation better, please share with us.
Java List Implementation Example
In this class DemoList.java
, we are creating a List implementation with following features:
- List may grow from zero to infinite size (at least theoretically).
- List will be initialized with minimum 10 elements at the time of creation.
- List will provide methods for fetching, adding, removing and printing the list at any state in its lifecycle.
Sourcecode of List Implementation
package com.howtodoinjava.datastructure; import java.util.Arrays; public class DataList<E> { //Size of list private int size = 0; //Default capacity of list is 10 private static final int DEFAULT_CAPACITY = 10; //This array will store all elements added to list private Object elements[]; //Default constructor public DataList() { elements = new Object[DEFAULT_CAPACITY]; } //Add method public void add(E e) { if (size == elements.length) { ensureCapacity(); } elements[size++] = e; } //Get method @SuppressWarnings("unchecked") public E get(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } return (E) elements[i]; } //Remove method @SuppressWarnings("unchecked") public E remove(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } Object item = elements[i]; int numElts = elements.length - ( i + 1 ) ; System.arraycopy( elements, i + 1, elements, i, numElts ) ; size--; return (E) item; } //Get Size of list public int size() { return size; } //Print method @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for(int i = 0; i < size ;i++) { sb.append(elements[i].toString()); if(i<size-1){ sb.append(","); } } sb.append(']'); return sb.toString(); } private void ensureCapacity() { int newSize = elements.length * 2; elements = Arrays.copyOf(elements, newSize); } }
Let’s quickly test out our List implementation.
package com.howtodoinjava.datastructure; public class Main { public static void main(String[] args) { DataList<Integer> list = new DataList<>(); //Add elements list.add(1); list.add(2); list.add(3); System.out.println(list); //Remove elements from index list.remove(2); System.out.println(list); //Get element with index System.out.println( list.get(0) ); System.out.println( list.get(1) ); //List Size System.out.println(list.size()); } }
Output: [1,2,3,4,5] [1,2,4,5] 1 2 4
As verified in above output, our list implementation is capable of providing all necessary features.
Happy Learning !!
Leave a Reply