我是java新手。 在java中我可以看到int和Integer是不同的。 int 是原始类型,Integer 是类。 我已经完成了以下代码。
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class Student {
private Integer roleNo;
private String name;
private String city;
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Student> lstStudent = new LinkedList<Student>();
lstStudent.add(new Student(111, "aaa", "Moon"));
lstStudent.add(new Student(333, "ccc", "Sun"));
lstStudent.add(new Student(222, "bbb", "Jupiter"));
List<Student> sortedStudents = lstStudent.stream().sorted(Comparator.comparing(Student::getRoleNo))
.collect(Collectors.toList());
System.out.println(sortedStudents);
}
}
我在 sortedstudent
列表中给出了断点,我可以看到我正在获取所有值,但没有获取整数值。它显示为“整数”……为什么?
我在这里遗漏了一些关键概念吗?
最佳答案
这个answer这里很好地解释了发生了什么:
Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).
To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.
就像评论中的@NicholasK
所说;如果您在调试器中展开 Integer
对象,您将看到它是一个包含一个名为 value
e 的字段的对象,该字段保存表示为基元 的实际值int
.
虽然您可以在 IDE 中亲自看到这一点,但这里有一个屏幕截图,可为所有可能偶然发现此问题并有相同问题的人提供更多背景信息:
了解更多关于Java Debugging with Eclipse的信息.
关于java - 我在 Java 8 代码的列表中得到的整数值为 'Integer',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407306/