Hashcode overload is improperly caused by memory leakage

xiaoxiao2021-03-06  105

Import java.util.hashset;

Import java.util.set;

/ **

* If the Hashcode's method is improper, it is easy to cause memory leaks, especially when SET is static.

* And, the middle is easy to appear strange phenomena, clearly added to the set, but the Contains method returns false

* /

Public class hashtest {

Public static void main (String [] args) {

Set hashset = new hashset ();

STUDENT = new student ();

Student.setName ("a");

Student.setno ("M");

Hashset.add (student);

Student.setName ("AAAAA");

Boolean isok = hashset.contains (student);

System.out.println (ISOK);

Hashset.add (student);

INT size = hashset.size ();

System.out.println (size);

Hashset.remove (student);

SIZE = hashset.size ();

System.out.println (size);

}

}

Class student {

Public student () {

}

PRIVATE STRING NAME;

Private string NO;

Public string getname () {

Return Name;

}

Public string getno () {

Return NO;

}

Public void setname (String string) {

Name = string;

}

Public void setno (string string) {

NO = String;

}

Public Int hashcode () {

Return no.hashcode () Name.hashcode ();

}

}

Execute the above program, the result may be a bit out of your expectations. If the set declares a Static member of a class, the HashSet will always end the "Forgotten" object until the program exits. If a similar code is running on the server, the result is conceivable. Don't think that this situation is not common, this is the best way to lead to memory leaks in Java. For example, those generated in Hibernate, if the influence generated in the operation, Hibernate uses a cache mechanism, believes, after running for a while, your program does not appear out of OutofMemory!

转载请注明原文地址:https://www.9cbs.com/read-97303.html

New Post(0)