gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:49:05 25 4
gpt4 key购买 nike

因此,作为练习,我创建了此类“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com