我在Java中的代碼中遇到性能問題。我必須計算一個進程創建的每個對象的頻率。對象的類型是下面給出的「節點」。 目前我已經在test1中使用下面給出的HashMap類型技術解決了這個問題。然而,這個過程非常緩慢,因爲我的模擬生成了數百萬個對象。此外,我必須在每次迭代期間拆分字符串,然後重新連接,等等。所以我正在考慮像下面在test2中給出的那樣應用技術。但是HashMap會將每個新對象視爲新條目,而不管對象內的內容如何。 我想知道如果有人知道如何有效地解決這個問題。您Node
類中Java中的性能問題
public class NewMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String[] a={"c","d"};
int[] b={1,2};
Map<String, Integer> test1=new HashMap<>();
test1.put(new Node(a, b).toString(), 1);
test1.put(new Node(a, b).toString(), 3);
System.out.println(test1.size()); // size is 1
//////////////////////////
Map<Node, Integer> test2=new HashMap<>();
test2.put(new Node(a, b), 1);
test2.put(new Node(a, b), 3);
System.out.println(test2.size()); // size is 2
}
}
class Node{
String[] a;
int[] b;
public Node(String[] a, int[] b) {
this.a = a;
this.b = b;
}
public String toString(){
String result=null;
for(String e:a)
result+=e+"|";
for(int e:b)
result+=e+"|";
return result;
}
}
覆蓋'hashCode'你'Node'類? – 2014-09-11 00:28:51
@ C.B。和'equals' – resueman 2014-09-11 00:30:18
您使用'String'而不是'Node'作爲關鍵字的任何特定原因? – Amadan 2014-09-11 00:31:21