张老师,在讲高新的时候第二十六个视频中,讲到内存泄露问题下面代码
- package collectionDemo;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.HashSet;
- public class CollectionTest {
- public static void main(String[] args) {
- Collection collections = new HashSet();
- Point p1 = new Point(3,3);
- Point p2 = new Point(5,5);
- Point p3 = new Point(3,3);
- Point p4 = new Point(3,3);
-
- System.out.println(p1.hashCode()+"---------"+p1.toString());
- System.out.println(p3.hashCode()+"---------"+p3.toString());
- collections.add(p1);
- collections.add(p2);
- collections.add(p3);
- collections.add(p4);
- p1.y = 7;
- System.out.println(p1.hashCode()+"---------"+p1.toString());
- System.out.println(collections.size());
- collections.remove(p1);
- System.out.println(collections.size());
- }
- }
- class Point{
- private int x;
- public int y;
-
- public Point(int x, int y) {
- this.x = x;
- this.y = y;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + x;
- result = prime * result + y;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Point other = (Point) obj;
- if (x != other.x)
- return false;
- if (y != other.y)
- return false;
- return true;
- }
-
- }
复制代码
接下来,说一下我浅显的看法,在集合中存储的是对象的引用,当p1.y=7的时候,p1的引用已经发生改变,但是此时集合中的引用并没有被改变,当你调用collection的contains或者remove方法时,你传入的参数是p1,但是此时p1的引用已经改变,所以集合中找不到这个引用,就更不能删除了,因此会出现,内存泄露的现象。
求指教 |
|