zoukankan      html  css  js  c++  java
  • 自制数据结构(容器)-java开发用的最多的ArrayList和HashMap




    public class MyArrayList<E> { private int capacity = 10; private int size = 0; private E[] values = null; @SuppressWarnings("unchecked") public MyArrayList() { values = (E[]) new Object[capacity]; } @SuppressWarnings("unchecked") public MyArrayList(int capacity) { this.capacity = capacity; values = (E[]) new Object[this.capacity]; } public void put(E e) { if (e == null) { throw new RuntimeException("The value should not be null."); } if (size >= capacity) { enlargeCapacity(); } values[size] = e; size++; } public E get(int index) { if (index >= size) { throw new RuntimeException("The index:" + index + " is out of band."); } return values[index]; } public void remove(int index) { if (index >= size) { throw new RuntimeException("The index:" + index + " is out of band."); } for (int i = index; i < size - 1; i++) { values[i] = values[i + 1]; } values[size - 1] = null; size--; } @SuppressWarnings("unchecked") private void enlargeCapacity() { capacity = capacity * 2; E[] tmpValues = (E[]) new Object[capacity]; System.arraycopy(values, 0, tmpValues, 0, size); values = tmpValues; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < size; i++) { sb.append(values[i]).append(","); } if (size > 0) { sb.deleteCharAt(sb.length() - 1); } sb.append("]"); return sb.toString(); } /** * @param args */ public static void main(String[] args) { MyArrayList<Integer> myList = new MyArrayList<Integer>(); for(int i=0;i<1000;i++){ myList.put(i); } System.out.println(myList.toString()); } }

      

  • 相关阅读:
    今天地震了(有震感)...
    上班了!
    C++ 中explicit的作用
    DoModal 函数的用法
    [导入]C++ GUi 选择
    [导入]C++资源之不完全导引(完整版)[转]
    [导入]The GUI Toolkit, Framework Page
    [导入]C/C++中调用SQLITE3的基本步骤
    ACM
    牛客NOIP暑期七天营提高组5+普及组5
  • 原文地址:https://www.cnblogs.com/cs-lcy/p/7250181.html
Copyright © 2011-2022 走看看