开发者

can I copy an array to a hash table?

I hav开发者_Python百科e an array which its elements are float .how can I copy this array to a hash table?

thanks


You can easily put them into a Hashtable of int -> float. The following method will use their index in the array as the key.

float[] arr;
Hashtable<Integer, Float> table = new Hashtable<Integer, Float>(arr.length);
for (int i = 0; i < arr.length; i++) {
    table.put(i, arr[i]);
}


An array cannot directly correspond to a Map. It can correspond to a set.

new HashSet(Arrays.asList(array))


Hashtable implements Map, so you would need to pair every float with some key.


Given the OP's clarification of his/her requirements in jjnguy's answer, here's an O(n) (amortized) way to count occurrences of unique values in a float array:

float[] values;
Map<Float, Integer> occurrences = new HashMap<Float, Integer>();
for ( float f : values ) {
    int count = occurrences.containsKey(f) ? occurrences.get(f) : 0;
    occurrences.put(f, count+1);
}

//then find multiple occurrences by finding entries with a value > 0
for ( Entry<Float, Integer> entry : occurrences.values() ) {
    if ( entry.getValue() > 1 ) {
       System.out.println("Duplicate: " + entry.getKey());
    }
}

In practice it's usually smelly to use a float as a key to anything, or to use a float in a way that pretends it's a discrete value. Floating point types are typically used to simulate "continuous" values, where for all intents and purposes 7.000000000012 should be considered the same as 7.000000000013.


If you want to know how many there are of different float values in your array, the best solution would be a multiset (which is typically built on top of a Map<T, Integer>). With Guava, you could do this:

float[] floats = ...
Multiset<Float> multiset = HashMultiset.create(Floats.asList(floats));
for (Multiset.Entry<Float> entry : multiset.entrySet()) {
  Float value = entry.getElement();
  int count = entry.getCount();
  ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜