【发布时间】:2020-12-11 10:36:44
【问题描述】:
一天前我决定开始学习 Java。我选择实现堆栈(链表实现)和其他数据结构来学习它,但我不太确定我的代码,以及 Java GC 的行为,你们能检查我的代码是对还是错吗?
很抱歉,我不认识任何 Java 专家来询问我是否做对了。
顺便说一句,我来自 C 和 C++,我对我的程序占用的内存非常满意。
我尝试运行这个程序并推送了 500mb 的内存,然后当我使用 .pop() 方法时内存没有下降,我也等了大约 20 分钟,但没有任何反应。 我读到的是 java 会自动为我们释放内存,但由于我没有看到它出现故障,所以感觉好像我做错了。
我的堆栈
import java.util.Scanner;
// ------------------------ node ------------------------
class node<type>{
type value;
node<type> prev;
node(type value){
this.value = value;
}
// for checking I guess
void recdisp(node<type> recurs){
if(recurs != null){
System.out.println(recurs.value);
recurs.recdisp(recurs.prev);
}
return;
}
}
// ------------------------ STACK ------------------------
class mystack<type>{
node<type> top;
mystack(type value){
top = new node<type>(value);
top.prev = null;
}
void push(type value){
node<type> buffer = new node<type>(value);
buffer.prev = top;
top = buffer;
buffer = null;
}
type pop(){
node<type> tmp;
if(top == null){
System.out.println("POP: Stack is Empty");
return null;
}
type pass = top.value;
tmp = top;
top = top.prev;
tmp = null;
return pass;
}
void peek(){
System.out.println("TOP VALUE : "+top.value);
}
void display(){
if(top != null)
top.recdisp(top);
else
System.out.println("Display: Stack is empty");
}
}
// ------------------------ MAIN CLASS ------------------------
public class myjava{
public static void main(String []args){
mystack<Integer> stacks = new mystack<Integer>(5);
stacks.pop();
stacks.pop();
stacks.pop();
stacks.display();
stacks.push(10);
stacks.push(20);
stacks.push(30);
stacks.push(40);
stacks.display();
}
}
【问题讨论】:
-
您对内存“下降”的预期究竟如何? JVM 通常不会将分配的 RAM 返回给 OS,因为它猜测如果它需要 500MB 一次,它会再次需要它。
-
@chrylis -cautiouslyoptimistic 哦,我明白了,我在看我系统的内存,我以为我可以看到它下降了,但是我怎么能看到我的程序在 java 中的内存使用情况虚拟机?,我的代码也有问题吗?
标签: java memory-management garbage-collection stack singly-linked-list