Epitheoritis 32
Epitheoritis 32

Reputation: 366

Hash map with long values

I would like to create a hash map that maps an object of type Element to long values. What I have done so far:

class Element {
  public int x;
  public int y;
}
public class HelloWorld
{
  public static void main(String[] args)
  {
    HashMap<Element, Integer> marks = new HashMap<Element, Integer>();
    Element e = new Element();
  }
}

From what I saw Integer is a wrapper that converts an int to an Object of int type. How could I do the same for long?

Upvotes: 0

Views: 4338

Answers (3)

gudok
gudok

Reputation: 4179

Another way of doing this would be to use fastutil library. Using and storing small objects (like in your case) in standard java containers may be inefficient. This library addresses this problem by providing separate container implementations for all primitive types.

In your case you can use Object2LongOpenHashMap.

Even better, because your keys are only 8 bytes long, you can fuse x and y into single long primitive and use Long2LongOpenHashMap (or Long2LongArrayMap). Something like this:

void put(Long2LongOpenHashMap map, Element key, long value) {
  long k = ((long)key.x << 32) | key.y;
  map.put(k, value);
}

Upvotes: 0

Gatusko
Gatusko

Reputation: 2598

How could I do the same for long?

All primitives have corresponding wrapper classes:

Primitive type  Wrapper class
boolean         Boolean
byte            Byte
char            Character
float           Float
int             Integer
long            Long
short           Short
double          Double

From Java Docs

Upvotes: 4

Aiyuni
Aiyuni

Reputation: 810

You can use Long, which is the object (wrapper) version of long. Java automatically handles this conversion for you with autoboxing.

See docs for more info: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Upvotes: 2

Related Questions