温馨提示×

java怎么自定义顺序表

小亿
83
2023-12-12 13:21:53
栏目: 编程语言

要自定义顺序表,你可以创建一个类来表示顺序表,并在类中定义适当的方法来操作该列表。以下是一个简单的示例:

public class MyArrayList {
    private int[] array;
    private int size;
    
    public MyArrayList() {
        array = new int[10];
        size = 0;
    }
    
    public void add(int value) {
        if (size == array.length) {
            expandArray();
        }
        array[size] = value;
        size++;
    }
    
    public int get(int index) {
        if (index >= 0 && index < size) {
            return array[index];
        } else {
            throw new IndexOutOfBoundsException();
        }
    }
    
    public void set(int index, int value) {
        if (index >= 0 && index < size) {
            array[index] = value;
        } else {
            throw new IndexOutOfBoundsException();
        }
    }
    
    public int size() {
        return size;
    }
    
    private void expandArray() {
        int[] newArray = new int[array.length * 2];
        System.arraycopy(array, 0, newArray, 0, array.length);
        array = newArray;
    }
}

在上面的示例中,我们创建了一个名为MyArrayList的类,它包含一个私有整数数组array和一个整数size表示列表的大小。我们还定义了几个方法来操作该列表:

  • add方法:用于向列表中添加元素。如果数组已满,则通过expandArray方法将数组扩展为原来的两倍。然后,将新元素添加到数组的末尾,并将size增加1。
  • get方法:用于获取指定索引位置上的元素。如果索引超出范围,则抛出IndexOutOfBoundsException异常。
  • set方法:用于设置指定索引位置上的元素。如果索引超出范围,则抛出IndexOutOfBoundsException异常。
  • size方法:用于获取列表的大小。

需要注意的是,上述示例只是一个简单的实现,仅用于说明如何自定义顺序表。实际应用中,你可能需要添加更多的方法来支持其他操作,例如删除元素、插入元素等。

0