search
HomeJavajavaTutorialExample of ArrayList custom imitation source code in Java

This article mainly introduces the relevant information about imitating source code customization in Java ArrayList. Friends in need can refer to

Java Imitate the source code to customize ArrayList

I recently looked at the source code of ArrayList and took the time to write a custom ArrayLsit with simple functions and no generics based on the underlying structure of ArrayList to help me better understand ArrayList:. The underlying data structure implemented is a group of Object, and the code is as follows:

/** 
 * 自己实现一个ArrayList 
 * 
 */ 
public class MyArrayList { 
   
  private Object[] elementData; 
  private int size; 
   
   
  public int size(){ 
    return size; 
  } 
   
  public boolean isEmpty(){ 
    return size==0; 
  } 
  //默认容量为10 
  public MyArrayList(){ 
    this(10); 
  } 
  /** 
   * 自定义容量 
   * @param initialCapacity 
   */ 
  public MyArrayList(int initialCapacity){ 
    if(initialCapacity<0){ 
      try { 
        throw new Exception(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
    elementData = new Object[initialCapacity]; 
  } 
  /** 
   * 添加一个元素 
   * @param obj 
   */ 
  public void add(Object obj){ 
    //数组扩容和数据的拷贝,重新new一个数组 
    if(size==elementData.length){ 
      Object[] newArray = new Object[size*2+1]; 
      System.arraycopy(elementData, 0, newArray, 0, elementData.length); 
 
      elementData = newArray; 
    } 
     
    elementData[size++]=obj; 
//   size++; 
  } 
  /** 
   * 通过索引获取元素 
   * @param index 
   * @return 
   */ 
  public Object get(int index){ 
    rangeCheck(index); 
     
    return elementData[index]; 
  } 
  /** 
   * 通过索引删除元素 
   * @param index 
   */ 
  public void remove(int index){ 
    rangeCheck(index); 
     
    int numMoved = size - index - 1; 
    if (numMoved > 0){ 
      System.arraycopy(elementData, index+1, elementData, index, 
          numMoved); 
    } 
    elementData[--size] = null; // Let gc do its work 
  } 
  /** 
   * 删除对应的元素(利用equal判断元素是否一致) 
   * @param obj 
   */ 
  public void remove(Object obj){ 
    for(int i=0;i<size;i++){ 
      if(get(i).equals(obj)){ //注意:底层调用的equals方法而不是==. 
        remove(i); 
      } 
    } 
  } 
  /** 
   * 设置索引对应的元素 
   * @param index 
   * @param obj 
   * @return 
   */ 
  public Object set(int index,Object obj){ 
    rangeCheck(index); 
 
    Object oldValue = elementData[index]; 
    elementData[index] = obj; 
    return oldValue; 
  } 
  /** 
   * 将元素插入对应的位置 
   * @param index 
   * @param obj 
   */ 
  public void add(int index,Object obj){ 
    rangeCheck(index); 
     
    ensureCapacity(); //数组扩容 
     
    System.arraycopy(elementData, index, elementData, index + 1, 
         size - index); 
    elementData[index] = obj; 
    size++; 
  } 
  /** 
   * 数组扩容 
   */ 
  private void ensureCapacity(){ 
    //数组扩容和数据的拷贝 
        if(size==elementData.length){ 
          Object[] newArray = new Object[size*2+1]; 
          System.arraycopy(elementData, 0, newArray, 0, elementData.length); 
//             for(int i=0;i<elementData.length;i++){ 
//               newArray[i] = elementData[i]; 
//             } 
          elementData = newArray; 
        } 
  } 
   
  /** 
   * 数组下标检查 
   * @param index 
   */ 
  private void rangeCheck(int index){ 
    if(index<0||index>=size){ 
      try { 
        throw new Exception(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
   
   
  public static void main(String[] args) { 
    MyArrayList list = new MyArrayList(3); 
    list.add("333"); 
    list.add("444"); 
    list.add("5"); 
    list.add("344433"); 
    list.add("333"); 
    list.add("333"); 
    for (int i = 0; i < list.size(); i++) { 
      System.out.println(list.get(i));  
    } 
    System.out.println("------------------------------");  
    list.remove("444"); 
    list.add(2, "a"); 
    for (int i = 0; i < list.size(); i++) { 
      System.out.println(list.get(i));  
    } 
  } 
 
}

Test result:

333

444

5

344433

333

333

------------------------------

333

5

a

344433

333

333

The above is the detailed content of Example of ArrayList custom imitation source code in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.