How to implement an ArrayList structure in Java - Tutorial

List implementations in Java

This article describes how to implement a list data structure in Java.

The implementations in this articles are for demonstration and education purpose. They do not try to be as efficient as the standard libraries and they are not intended to be an replacement for the standard Java libraries structures.


Table of Contents

1. List
2. About this website
2.1.
3. Links and Literature

1. List

The following example is contained in the project called de.vogella.datastructures.list.

List represents a data structure which allows to dynamically add, access and remove objects of the same type. Adding objects to the list is usually done via the add() method. The get(int i) method allows to retrieve the element at position i.

package de.vogella.datastructures.list;

import java.util.Arrays;

public class MyList<E> {
  private int size = 0;
  private static final int DEFAULT_CAPACITY = 10;
  private Object elements[];

  public MyList() {
    elements = new Object[DEFAULT_CAPACITY];
  }

  public void add(E e) {
    if (size == elements.length) {
      ensureCapa();
    }
    elements[size++] = e;
  }

  private void ensureCapa() {
    int newSize = elements.length * 2;
    elements = Arrays.copyOf(elements, newSize);
  }

  @SuppressWarnings("unchecked")
  public E get(int i) {
    if (i>= size || i <0) {
      throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i);
    }
    return (E) elements[i];
  }
}

  

The following show contains a small JUnit test for the data structure. I use in the first test the MyList implementation and in the second test the standard Java List implementation.

package de.vogella.datastructures.list;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class MyListTest {

  @Test(expected=IndexOutOfBoundsException.class)
  public void testMyList() {
    MyList<Integer> list = new MyList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(3);
    list.add(4);
    assertTrue(4 == list.get(4));
    assertTrue(2 == list.get(1));
    assertTrue(3 == list.get(2));

    list.get(6);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void testNegative() {
    MyList<Integer> list = new MyList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(3);
    list.add(4);
    list.get(-1);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void testList() {
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(3);
    list.add(4);
    assertTrue(4 == list.get(4));
    assertTrue(2 == list.get(1));
    assertTrue(3 == list.get(2));

    list.get(6);
  }

}

  

Tip

You typically also have the remove(int i) method to remove the element at position i but I leave this implementation for the reader. To delete elements in your list just shift all elements after position i one position to the left and decrease size.

时间: 2024-10-23 02:05:43

How to implement an ArrayList structure in Java - Tutorial的相关文章

How to implement common datastructures (List, Stack, Map) in plain Java - Tutorial

List, Map and Stack implementations in Java This article describes how to implement data structures (List Stack, Map) in Java. The implementations in this articles are for demonstration and education purpose. They do not try to be as efficient as the

Item 3 - What is an efficient way to implement a singleton pattern in Java?

Depending on the usage, there are several "correct" answers. Since java5 the best way to do it is to use an enum: public enum Foo { INSTANCE; } The Right Way to Implement a Serializable Singleton public enum Elvis { INSTANCE; private final Strin

LeetCode 232题用栈实现队列(Implement Queue using Stacks) Java语言求解

题目链接 https://leetcode-cn.com/problems/implement-queue-using-stacks/ 题目描述 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部.pop() -- 从队列首部移除元素.peek() -- 返回队列首部的元素.empty() -- 返回队列是否为空. 示例: MyQueue queue = new MyQueue();queue.push(1);queue.push(2); queue.peek(); //

[LeetCode] 211. Add and Search Word - Data structure design Java

题目: Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one le

Data structure basics - Java Implementation

Stack & Queue Implementations FixedCapacityQueue package cn.edu.tsinghua.stat.mid_term; import java.util.Objects; /** * Created by shuaiyi on 04/11/2017. */ public class FixedCapacityQueue<T> { private int size; private int head; private int tai

Split / Partition a collection into smaller collections - Java - Tutorial

Partition a collection into smaller collections This article describes how to partition a collections into a given number of smaller collections. Table of Contents 1. Partition a collection 2. Partition collection in Java 2.1. Implementation 2.2. Tes

Java Tutorial

http://www.tutorialspoint.com/java/index.htm

Java tutorial 02

一.EnumTest.java枚举类型 1 public class EnumTest { 2 public static void main(String[] args) { 3 Size s=Size.SMALL; 4 Size t=Size.LARGE; 5 //s和t引用同一个对象? 6 System.out.println(s==t); // 7 //是原始数据类型吗? 8 System.out.println(s.getClass().isPrimitive()); 9 //从字符串

java 指导 (Java Tutorial)

case1: site:docs.oracle.com -xmx -xms case2: site:docs.oracle.com thread case3: site:docs.oracle.com transient case4: site:docs.oracle.com interface case5: site:docs.oracle.com ManagementFactory etc