java - 当使用 new-operator 调用堆中的 Class() 进行多次调用时会发生什么?

标签 java object new-operator heap-memory dynamic-memory-allocation

当我们调用如下电话时:-

class Class{
int x;
public Class(int a){
 x = a;
}
public void display(){
 System.out.println(x);
}
}

然后在 main 方法中,我们使用类的对象来显示数据:-

new Class(5).display();    // object 1
new Class(7).display();    // object 2

现在,我的问题是:-

Whether what I've represented from object 1 and object 2 will be equal or distinct(in terms of memory locations in heap)? Whether two separate memory locations will be created in heap(dynamic memory allocator) OR whether the same object(memory location in heap) will be used?

我长期以来一直有这种困惑。而且我只是一个Java菜鸟。

请详细说明使用 new 调用对 Class 对象的堆部分/动态内存分配。

最佳答案

当您使用 new 运算符创建两个对象时,它们会在堆中将您作为不同的对象进行查找。因此,如果您将其与 == 进行比较,它们不会有多大。但是,如果您的代码是 JIT 编译的,则根本不会发生堆分配,因为 JIT 编译器足够智能,可以内联构造函数和 display() 方法,并得出结论,可以将其重写为

System.out.println(5);
System.out.println(7);

但是如果您实际上将它们与 == 进行比较,那么可能会关闭此优化,并且将在堆上分配两个不同的对象。

关于java - 当使用 new-operator 调用堆中的 Class() 进行多次调用时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142550/

相关文章:

java - SimpleJpaRepository 不修改持久化实体

java - 用于 SDL Tridion 2011 的 Java 部署程序扩展的原型(prototype)或方法,用于将内容索引到 Apache Solr

javascript - 使用 JavaScript 自定义比较函数合并两个对象数组

java - 卡片布局显示错误的面板

javascript - 访问对象中的嵌套键并将它们与其他对象键进行比较,但第二个是对象数组

java - 如何在不使用 Maven 的情况下设置 Selenium WebDriver?

java - 获取下一个序列号

c++ - `new (std::nothrow)`是如何实现的?

c++ - "placement new"有什么用?

c++ - 什么时候重载 operator new?