从整数包装类转换为 int 基元类



>我一直在尝试将整数包装类转换为 int 基元类。我还没有找到使代码编译的正确方法。我正在使用Intellij IDEA,Java 11 Amazon Coretto,但我需要在运行java 8的计算机上运行它。

下面是原始代码:

static class Line<Integer> extends ArrayList<Integer> implements Comparable<Line<Integer>> {
@Override
public int compareTo(Line<Integer> other) {
int len = Math.min(this.size(), other.size());
for (int i = 0; i < len; i++) {;
if ((int) this.get(i) != (int) other.get(i)) {
if ((int this.get(i) < (int) this.get(i)) {
return -1;
} else if ((int) this.get(i) > (int)this.get(i)) {
return 1;
} else {}
}
}
...

请注意,该行将插入到数组列表中。

最初,我对所有 Integer 对象都使用了强制强制转换,所以它会像(int) this.get(i).它在我的本地终端上工作,我的Intellij对此并不担心,但不幸的是,另一台计算机没有。它无法在那里编译

我以为是因为强制投射,因为另一台电脑回来了

Main.java:159: error: incompatible types: Integer cannot be converted to int
if ((int) this.get(i) != (int) other.get(i)) {
^
where Integer is a type-variable:
Integer extends Object declared in class Line

所以我将它们全部删除,并认为我可以让机器自行拆箱 Integer 包装器。它仍然没有编译。

如果代码保留如上面写的内容(无强制强制转换(,它将返回"运算符'<'不适用于'整数'、'整数'" 所以我使用了 .compareTo(( 方法。编译错误。

然后我尝试将它们分配给一个 int 变量。Intellij IDEA对我尖叫,它需要int,但找到了Integer。所以我强行施法,就像这样

int thisLine = (int) this.get(i);
int otherLine = (int) other.get(i);
if (thisLine != otherLine) {
if (thisLine < otherLine) {
return -1;
} else if (thisLine > otherLine) {
return 1;
} else {}

不,没用。拆除石膏也不起作用。

这次我查找了Javadocs(https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#intValue--(关于Integer类,并发现了一个名为intValue((的有前途的小方法。问题是?Intellij无法解析该方法(奇怪的是,VSCode不认为这是一个错误(。我是这样用的

int thisLine = this.get(i).intValue();
int otherLine = other.get(i).intValue();
if (this.get(i) != other.get(i)) {
if (thisLine < otherLine) {
return -1;
} else if (thisLine > otherLine) {
return 1;

果然,那台顽固的计算机上又出现了一个编译错误。

我没办法了。我正在认真考虑创建一个新的自定义类,以便我可以将 int 值存储在 ArrayList 中,而不必处理所有这些 Java 向后不兼容的废话。 这里有人知道在 Java 中将整数包装器对象转换为 int 原始对象的一致方法吗?

这是错误消息中解释它的线索:

其中 Integer 是一个类型变量:

整数扩展 在类 Line 中声明的对象

Integer不是java.lang.Integer而是一个名称混乱的类型变量......

您在此处声明了类型变量:

static class Line<Integer> extends ArrayList<Integer> implements Comparable<Line<Integer>>

就好像你这样声明它一样:

static class Line<T> extends ArrayList<T> implements Comparable<Line<T>>

但是通过将类型变量命名为Integer而不是T,然后尝试将类型T的对象强制转换为稍后int

通过不声明名为Integer的类型参数来修复它,这里不需要它:

static class Line extends ArrayList<Integer> implements Comparable<Line<Integer>>

你根本不应该将整数转换为 int。整数类有.compareTo比较两个整数的方法。

0 表示值 1 等于值 2。-1 表示值 1 小于值 2,1表示值 1 大于值 2。

请尝试以下操作:

public int compareTo(Line<Integer> other) {
//get the smallest length
int len = this.size() <= other.size() ? this.size() : other.size();
for (int i = 0; i < len; i++) {
int compare = this.get(i).compareTo(other.get(i));
if (compare != 0) { //if compare is not zero they are not the same value
return compare;
}
}
//If we get here, everything in both lists are the same up to "len"
return 0;
}

compareTo(( 方法是 java 下 Integer 类的一个方法。 lang 包。...如果整数相等,则返回值 0 的结果 到参数 Integer,如果 Integer 小于 参数 Integer 和大于 0 的值(如果 Integer 更大( 比参数整数。

在你类中,"Integer"不是一个java.lang.Integer,而是一个泛型类,这就是原因

相关内容

最新更新