简体   繁体   English

哪种Java数据结构最适合我的应用程序?

[英]Which is the best Java Data structure for my application?

My problem statement is like that when i get a data , i store it in a data structure and keep a counter.If something similar comes then by searching it in the data structure if similar thing is already present there then just increment the counter and there is no limit of my data. 我的问题陈述是,当我获取数据时,我将其存储在数据结构中并保留一个计数器。如果有类似的东西出现,则在数据结构中搜索它(如果已经存在类似的东西),则只需增加计数器并在那里对我的数据没有限制。 The data can be sometimes very larger.So being a beginner in java i want to know which data structure would be good/efficient for my problem. 数据有时可能会非常大。因此,作为Java的初学者,我想知道哪种数据结构对我的问题会是好的/有效率的。

You want a HashMap, with whatever your "data" as the key, and a counter as the value. 您需要一个HashMap,将您的“数据”作为键,并将计数器作为值。

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html

The reason it's a good choice is because it has O(1) "contains" checking, retrieval, and insertion time. 之所以选择它是一个好选择,是因为它具有O(1)“包含”检查,检索和插入时间。 As long as you don't need to sort your data, it's an excellent choice. 只要您不需要对数据进行排序,这就是一个很好的选择。

This untested code should get you started. 这个未经测试的代码应该可以帮助您入门。 Replace String with the type of your data. String替换为数据类型。 If it's a custom class, you must overload hashCode() and equals() . 如果是自定义类,则必须重载hashCode()equals()

HashMap<String, Integer> map = new HashMap<String, Integer>();

...

Integer i = map.get(data);
if(i == null) {
   map.put(data, 1);
} else {
   map.put(data, i + 1);
}

Sound like you need to use a HashMap<YourClass, Integer> ( link ). 听起来好像您需要使用HashMap<YourClass, Integer>link )。

The value is the counter, that's why it is integer. 该值是计数器,这就是为什么它是整数。 when something comes you check to see if an item with that key exists. 当有东西出现时,您检查是否存在具有该钥匙的物品。 If not you add it (with a value of 1), otherwise you add it with a value of one plus the previous value. 如果不是,则将其添加(值为1),否则将其添加为1加上前一个值。

You can optimize on that by instead of Integer make your value be a custom class, which wraps an integer and allows to be incremented. 您可以对此进行优化,而不是使用Integer来使您的值成为自定义类,该类包装一个整数并允许递增。 This way you won't have to insert into the hash map every time when you increment. 这样,您每次增加时就不必每次都插入到哈希图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM