java - 无法在类中的两个数组之间使用相等运算符来模仿 ArrayList 的工作原理

标签 java arrays arraylist

因此,作为练习,我创建了此类“Array”来模仿普通的 ArrayList 如何与我想要的一些附加函数配合使用。

我遇到了名为“相交”的方法的问题。 在此方法中,假设发生的是它获取两个输入的数组(来 self 创建的数组类)对象并比较它们中的值。如果两个数组之间有公共(public)数字,它会创建一个新数组并将它们放入这个新数组中。这样,我就可以打印这个新数组中的值。

但是,我不能在这里使用等于运算符,因为我需要普通的 Java 数组类型,而不是我为我使用的参数“Array secondaryArray”创建的类。 因此,我可以像这样使用 If 语句: if (array[i] == secondaryArray[j])

我该如何解决这个问题?

这是主类:

package com.company;

public static void main(String[] args) {

    Array array = new Array(3);
    Array array1 = new Array(3);

    array.insert(1);
    array.insert(2);
    array.insert(3);

    array1.insert(2);
    array1.insert(3);
    array1.insert(4);

    array.print();
}

}

这是我制作的数组类:

public class Array {
 int length;
 Integer[] array;

public Array(int length) {
    array = new Integer[this.length=length];
}

public void insert(int item) {

    if (array[length - 1] == null) { //if there is no value in the last index
        for (int i = 0; i < length; i++) {
            if (array[i] == null) {
                array[i] = item;
                break;
            }
        }
    } else if (array[length - 1] != null) { //if there is a value in the last index
        int newLength = this.length + 1;
        Integer[] newArray = new Integer[newLength];

        for (int j = 0; j < newLength; j++) {
            for (int i = 0; i < length; i++) {
                if (i == j) {
                    newArray[j] = array[i];
                }
            }
        }
        newArray[newLength - 1] = item;
        this.array = newArray;
        this.length = newLength;
    }
}

public int intersect(Array secondArray) {
    //Store array1 and array2
    //Go through all of the values in each array
    //If the values are equal, store them in another array
    Integer[] commonValues = new Integer[length];

    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < secondArray.length; j++) {
            if (array[i] == secondArray[j]) {

            }
        }
    }
    return commonValues[0];
}

}

最佳答案

I however can't use the equal operator here because I need the normal Java Array type and not the class I made for the argument "Array secondArray" that I have used. Due to this, I can use the If statement like this: if (array[i] == secondArray[j])

由于java不支持custom indexers这将允许您编写 myCustomArray[i] == myCustomArray2[i],您将需要使用方法来获取元素。做类似 ArrayList 的事情执行:myCustomArray.get(i) == myCustomArray2.get(i)

关于java - 无法在类中的两个数组之间使用相等运算符来模仿 ArrayList 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60899829/

相关文章:

arrays - 无法聚合数组

javascript - 在数组中存储对值的引用,然后重新分配原始变量 (JavaScript)

java - ArrayList索引?

Java ArrayList for-loop lcv 被认为是一个对象,而不是一个 int

java - 具有多个对象的 MVC 模式

java - 需要 HTML 页面作为从一个应用程序到另一应用程序的响应

java - 如何将泛型类型的类传递给Java中的方法?

c - 如何在 C 中使用二维指针数组来存储字符串?

java - 如何找到NDK的路径?

java - NiFi - 更新处理器中的 Luwak (Lucene) 索引