java中,自己写的entity类如何进行清空?
问题描述:
假如我现在有个Student类,查了百度,大部分给的方法就是Student student=new Student(),相当于再创建一个对象,但是这样的效果就是数据量太大的时候(特别是new的对象在循环里)内存要炸,后来我发现像是Hashmap之类有.clear()方法,这样就是对同一个对象进行操作而不用在内存中新建对象,那么自己写的类如何实现这种.clear()方法呢?
答
等你把这道题搞懂你就知道为什么需要重新new一个对象,而不是清空原对象的的值了。
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
Map<Integer, Person> map = new LinkedHashMap<>();
Person person = new Person();
for(int a = 0;a<list.size();a++){
person.setNum(a);
person.setValue(list.get(a));
System.out.println(person);
map.put(person.getNum(),person);
}
for(Map.Entry<Integer, Person> entry : map.entrySet()){
System.out.println("key= " + entry.getKey() + " and value= "
+ entry.getValue().getValue());
}
//打印为key= 0 and value= cc
//key= 1 and value= cc
//key= 2 and value= cc
}
答
import java.util.*;
public class Hash_Map_Demo {
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
// Mapping string values to int keys
hash_map.put(10, "Geeks");
hash_map.put(15, "4");
hash_map.put(20, "Geeks");
hash_map.put(25, "Welcomes");
hash_map.put(30, "You");
// Displaying the HashMap
System.out.println("Initial Mappings are: " + hash_map);
// Clearing the hash map using clear()
hash_map.clear();
// Displaying the final HashMap
System.out.println("Finally the maps look like this: " + hash_map);
}
}