• 线性表


    这个比较重要希望看完能理解

    代码如下:

    十个方法:
    package Day07;

    import java.util.Arrays;

    public class MyArrayList {
    public static final int DEFAULT_CAPACITY = 1;
    private int size = 0;
    private Object[] elements;
    /**
    *
    */
    public MyArrayList() {
    this.size = 0;
    this.elements = new Object[DEFAULT_CAPACITY];
    }
    public int getSize() {
    return size;
    }
    public Object[] getElements() {
    return elements;
    } public void add(Object o) {
    if (size >= elements.length) {
    Object[] temp = new Object[elements.length * 2];
    for (int i = 0; i < elements.length; i++) {
    temp[i] = elements[i];
    }
    elements = temp;
    }
    elements[size++] = o;
    }

    public void add(int index, Object o) {
    if (size >= elements.length) {
    Object[] temp = new Object[elements.length * 2];
    for (int i = 0; i < elements.length; i++) {
    temp[i] = elements[i];
    }
    elements = temp;
    }
    elements[index] = o;
    size++;
    }

    public void clear() {
    for (int i = 0; i < size; i++) {
    elements[i] = null;
    }
    }

    public boolean contains(Object o) {
    boolean isInArray = false;
    for (int i = 0; i < size; i++) {
    if (elements[i].equals(o)) {
    isInArray = true;
    break;
    }
    }
    return isInArray;
    }

    public Object get(int index) {
    return elements[index];
    }

    public int indexOf(Object o) {
    int index = -1;
    for (int i = 0; i < size; i++) {
    if (elements[i].equals(o)) {
    index = i;
    break;
    }
    }
    return index;
    }

    public boolean isEmpty() {
    return this.size == 0;
    }

    public void set(int index, Object o) {
    if (index >= 0 && index < size) {
    elements[index] = o;
    } else {
    System.out.println("index out of bound.");
    }
    }

    public int size() {
    return this.size;
    }

    public static void main(String[] args) {
    MyArrayList arr1 = new MyArrayList();
    arr1.add("abc");
    arr1.add("123");
    System.out.println(Arrays.toString(arr1.getElements()));
    System.out.println(arr1.contains("123"));
    System.out.println(arr1.contains("1"));
    }
    }

    只相信苦尽甘来
  • 相关阅读:
    类加载器ClassLoader
    JAVA分别获取日期中的年、月、日
    sql 安全问题
    马尔科夫链
    触发器、锁、事务和事务控制
    索引、视图、存储过程、函数、游标
    字符集
    数据类型选择
    存储引擎
    错误:too many indices for array
  • 原文地址:https://www.cnblogs.com/F001li/p/7055909.html
Copyright © 2020-2023  润新知