重复内存分配 Java
Duplicate Memory Allocation Java
在我的代码中,我有一个方法或多个方法声明了一些对象,例如:
public void method{
ArrayList <Integer> al = new ArrayList<>();
//do smth else
}
我多次调用这些方法。是否会因为调用新的操作符而在每次迭代中分配新的内存?
提前致谢!
是的,你每次迭代都会有一个新的内存分配,你可以这样做以避免多次内存分配
ArrayList <Integer> al = null; //make the declaration outside the method
public void method{
if (al == null){
al= new ArrayList<>();
}else{
al.clear();}
//do smthing with you're arrayList here
}
在我的代码中,我有一个方法或多个方法声明了一些对象,例如:
public void method{
ArrayList <Integer> al = new ArrayList<>();
//do smth else
}
我多次调用这些方法。是否会因为调用新的操作符而在每次迭代中分配新的内存? 提前致谢!
是的,你每次迭代都会有一个新的内存分配,你可以这样做以避免多次内存分配
ArrayList <Integer> al = null; //make the declaration outside the method
public void method{
if (al == null){
al= new ArrayList<>();
}else{
al.clear();}
//do smthing with you're arrayList here
}