gpt4 book ai didi

java - 从 Integer 包装类转换为 int 原始类

转载 作者:行者123 更新时间:2023-12-01 19:34:12 25 4
gpt4 key购买 nike

我一直在尝试将 Integer Wrapper 类转换为 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 {}
}
}
...

请注意,该 Line 已插入到 ArrayList 中。

最初我对所有 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

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

如果代码像上面写的那样(没有强制转换),它将返回“Operator '<'不适用于'Integer','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 {}

不,没用。移除类型转换也不起作用。

这次我查找了有关 Integer 类的 Javadocs ( https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#intValue-- ),并发现了一个很有前途的小方法,称为 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 中将 Integer 包装对象转换为 int 原始对象的一致方法吗?

最佳答案

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

where Integer is a type-variable:

Integer extends Object declared in class 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>>

关于java - 从 Integer 包装类转换为 int 原始类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58431746/

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