0

I have a large HashMap<Integer, MyObject> which is located on a server. I need to send a String from MyObject across a network to a client. My problem is that I can't figure out a good way to keep track of what MyObject has already been accessed to send the String.

I'd like it so that the client can repeatedly call the server's function to retrieve the String, then the client can add all the Strings to an ArrayList. The server would indicate all the Strings have been sent by returning null.

I can't simply send an ArrayList<String> of all the Strings as I am limited to a tiny message size due to the use of RSA encryption.

The only way I've thought of so far is to keep a static instance variable HashSet<Integer> that holds all of the already accessed MyObjects. But this would mean I'd have to cross reference the HashMap to the HashSet for every lookup. There must be a better way.

CS Student
  • 1,613
  • 6
  • 24
  • 40
  • you could create a custom class that does inherit from `HashMap` and hold a `Set`. You just would have to override `HashMap#get` which would also add the keyValue that you are looking for into your `Set`. – SomeJavaGuy Oct 22 '15 at 13:00
  • If you can use an instance variable of boolean type – SacJn Oct 22 '15 at 13:05

2 Answers2

1

This could be a tiny example of a Map that keeps track of the keys that did get accessed. Basicly it has just overriden the get method of HashMap and additionaly adds the Key that did get accessed into a Set

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class TrackMap<K, V>  extends HashMap<K,V>{
    private static final long serialVersionUID = 1L;

    Set<Object> usedKeys = new HashSet<>();

    @Override
    public V get(Object key) {
        usedKeys.add(key);
        return super.get(key);
    }

    public Set<Object> getUsedKeys() {
        return usedKeys;
    }

    public static void main(String[] args) {
        TrackMap<Integer, String> test = new TrackMap<>();
        for(int i = 0;i<100;++i) {
            test.put(i, Integer.toString(i));
        }
        System.out.println(test.get(5));
        System.out.println(test.get(10));
        System.out.println(test.get(15));
        System.out.println(test.get(17));
        System.out.println(test.get("what?"));

        for(Object i : test.getUsedKeys()) {
            System.out.println("The key " + i + " was accessed");
        }
    }
}
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

You may want to look into using an iterator to access the data of the HashMap

An iterator will go through every object in the map without duplicates, and you won't need to use a set to keep track of which objects you have already accessed

Iterate through a HashMap

Community
  • 1
  • 1
phflack
  • 2,729
  • 1
  • 9
  • 21