首页 > 解决方案 > Java:在定制的通用向量中间插入元素

问题描述

我正在尝试编写代码以将字符串/整数/空值插入到 JAVA 中的通用向量的中间。但这部分代码无法编译。可能是什么问题?谢谢你。我还添加了错误消息。

public synchronized void addToPosition (T element, int index) {
    if (index+1 == size-1) {
        ensureCapacity();
    }
    System.out.println("Add element to position:");
    Scanner scanner = new Scanner(System.in);
    index = scanner.nextInt();
    if (index < 0 || index > this.index-1) {
        throw new IndexOutOfBoundsException();
    }
    T[] newElementData = (T[]) new Object [size];
    for (i = 0; i < index; i++) {
        newElementData[i] = elementData[i];
    }
    System.out.println("Which element to add?");
    element = (T) scanner.nextLine();
    newElementData[index] = element;
    for (i = index+1; i < this.index; i++) {
        newElementData[i] = elementData[i+1];
    }
    elementData = newElementData;
    this.index++;
}

错误信息

标签: javagenericsvector

解决方案


正如您在评论中所说,您addToPosition()像这样调用该方法:

vectorList.addToPosition();

而方法签名如下:

public synchronized void addToPosition (T element, int index) {

所以他们不匹配。例如,您可以摆脱参数:

public synchronized void addToPosition () {
    T element;  // the values you will read later from user input
    int index;

推荐阅读