I am fairly new in Java, so I have to rely on this community for this one.
I need to store an object in some sort of array/list where I can quickly access the object using a string and two interger keys. Something like a["string"][1][1] - I have looked over some different guides and tutorials, but not been able to come up with a good solution that's easy to manage.
I am creating a Minecraft plugin where I need to keep track of where specific Blocks are with world, chunk_x, and chunk_z- I am trying to create a method where I can provide a location, which has the three beforementioned values, and do a quick look up based on the world and chunk, so I do not have to iterate all stored blocks in the world, but can limit it to 9 chunks of the world. (Current chunk i am in and all surrounding neighbours)
How about this:
Map<String, Object[][]> store;
Does it have to be a multidimensional array? You could use just a hash map with a custom key that holds your string key and the two integer keys. Here is a complete example of what I mean:
import java.util.HashMap;
import java.util.Objects;
public class multidim {
static class Key {
int index0, index1;
String str;
int _hash_code;
public Key(String s, int i0, int i1) {
_hash_code = Objects.hash(s, i0, i1);
str = s;
index0 = i0;
index1 = i1;
}
public int hashCode() {
return _hash_code;
}
public boolean equals(Object x) {
if (this == x) {
return true;
} else if (x == null) {
return false;
} else if (!(x instanceof Key)) {
return false;
}
Key k = (Key)x;
return (index0 == k.index0)
&& (index1 == k.index1)
&& Objects.equals(str, k.str);
}
}
public static void main(String[] args) {
HashMap<Key, Double> m = new HashMap<Key, Double>();
m.put(new Key("mjao", 3, 4), 119.0);
m.put(new Key("katt$k1t", 4, 6), 120.0);
System.out.println("Value that we put before: "
+ m.get(new Key("mjao", 3, 4)));
}
}
We define a class Key that represents the values you use to access elements and we override its equals and hashCode methods so that it can be used in a hash map. Then we just use it with the java.util.HashMap class. Running the above program will output Value that we put before: 119.0.
Edit: Add this == x comparison in equals (a small optimization).
What about combination of Map and Pair?
Map<String, Pair<Integer, Integer>> tripletMap = new HashMap<>;
tripletMap.put(Pair.with(23, 1););
You can access values from your triplet as any map and then retrieved Pair as:
Pair<Integer, Integer> myPair = tripletMap.get("key")
myPair.getValue0()
myPair.getValue1()
Related
I am trying to take in a List of strings and add them into a Priority Queue with Key and Value. The Key being the word and the value being the string value of the word. Then I need to sort the queue with the highest string value first. The priority queue is not letting me add 2 values.
public static List<String> pQSortStrings(List<String> strings) {
PriorityQueue<String, Integer> q = new PriorityQueue<>();
for (int x = 0; x < strings.size(); x++) {
q.add(strings.get(x),calculateStringValue(strings.get(x)));
}
return strings;
}
Problem
PriorityQueue can store a single object in it's each node. So what you are trying to do can not be done as it is.
But you can compose both objects in a single class and then use the PriorityQueue.
You would either need to supply a Comparator or rely on natural ordering by implementing Comparable interface.
Solution
Create a class which has String and int as it's members.
public class Entry {
private String key;
private int value;
// Constructors, getters etc.
}
Implement Comparable interface and delegate comparison to String.
public class Entry implements Comparable<Entry> {
private String key;
private int value;
public Entry(String key, int value) {
this.key = key;
this.value = value;
}
// getters
#Override
public int compareTo(Entry other) {
return this.getKey().compareTo(other.getKey());
}
}
Build the PriorityQueue using this class.
PriorityQueue<Entry> q = new PriorityQueue<>();
Add elements as following.
q.add(new Entry(strings.get(x), calculateStringValue(strings.get(x))));
Hope this helps.
Using Java-8
PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(Map.Entry.comparingByValue(Comparator.reverseOrder()));
to add a new Entry
queue.offer(new AbstractMap.SimpleEntry<>("A", 10));
Solution
public static List<String> pQSortStrings(List<String> strings) {
Queue<String> pq = new PriorityQueue<>((a, b) ->
calculateStringValue(b) - calculateStringValue(a));
for (String str : strings) {
pq.add(str);
}
return strings;
}
Explanation
I believe that the cleanest way to do this is to store Strings in your pq and use a small custom Comparator.
In this case, we want to use calculateStringValue and the pq should return highest String values first. Therefore, make a pq of entries and use the following Comparator:
1 Queue<String> pq = new PriorityQueue<>(new Comparator<String>() {
2 #Override
3 public int compare(String a, String b) {
4 return calculateStringValue(b) - calculateStringValue(a);
5 }
6 });
7 for (String str : strings) {
8 pq.add(str);
9 }
10 return strings;
Simpler syntax for the Comparator, replacing lines 1 - 6, is:
Queue<String> pq = new PriorityQueue<>((a, b) ->
calculateStringValue(b) - calculateStringValue(a));
If you wanted to return smallest String values first, you could just switch the order around for a and b in the Comparator:
...new PriorityQueue<>((a, b) -> calculateStringValue(a) - calculateStringValue(b));
In general, the pattern a - b sorts by smallest first, and b - a sorts by largest values first.
Many good answers are already present but I am posting this answer because no one has used hashmap in their answers.
You can also make the priority Queue from HashMaps bellow is the example for the same. I am creating a max priority queue.
Mind well here I am considering that your hashmap contains only one Entry
PriorityQueue<HashMap<Character, Integer>> pq = new PriorityQueue<>((a, b) -> {
char keyInA = a.keySet().iterator().next(); // key of a
char keyInB = b.keySet().iterator().next(); // key of b
return b.get(keyInB) - a.get(keyInA);
});
For Insertion of the value in the priority queue.
pq.add(new HashMap<>() {
{
put('a', 0);
}
});
Define a class with a key field and a value field
Class MyClass{
int key;
String value
}
Queue<MyClass> queue = new PriorityQueue<>(Comparotor.comparingInt(a -> a.key));
Adding to #Tanmay Patil Answer, If you are using Java 8, You can use lambda for more concise code as comparator interface is a functional interface.
public class CustomEntry {
private String key;
private int value;
public CustomEntry(String key, int value) {
this.key = key;
this.value = value;
}
// getters etc.
}
Now below is the updated code
public static List<String> pQSortStrings(List<String> strings) {
PriorityQueue<CustomEntry> q = new PriorityQueue<>((x, y) -> {
// since you want to sort by highest value first
return Integer.compare(y.getValue(), x.getValue());
});
for (int x = 0; x < strings.size(); x++) {
q.add(new CustomEntry(strings.get(x),calculateStringValue(strings.get(x))));
}
return strings;
}
To use this priority queue
CustomEntry topEntry = q.peek();
System.out.println("key : " + topEntry.getKey());
System.out.println("value : " + topEntry.getValue());
Same logic can be also be applied by using Map.Entry<String, Integer> provided by java for storing key, pair value
I have been running into this problem sometimes when programming.
Imagine I have a table of data with two columns. The first column has strings, the second column has integers.
I want to be able to store each row of the table into a dynamic array. So each element of the array needs to hold a string and an integer.
Previously, I have been accomplishing this by just splitting each column of the table into two separate ArrayLists and then when I want to add a row, I would call the add() method once on each ArrayList. To remove, I would call the remove(index) method once on each ArrayList at the same index.
But isn't there a better way? I know there are classes like HashMap but they don't allow duplicate keys. I am looking for something that allows duplicate entries.
I know that it's possible to do something like this:
ArrayList<Object[]> myArray = new ArrayList<Object[]>();
myArray.add(new Object[]{"string", 123});
I don't really want to have to cast into String and Integer every time I get an element out of the array but maybe this is the only way without creating my own? This looks more confusing to me and I'd prefer using two ArrayLists.
So is there any Java object like ArrayList where it would work like this:
ArrayList<String, Integer> myArray = new ArrayList<String, Integer>();
myArray.add("string", 123);
Just create simple POJO class to hold row data. Don't forget about equals and hashCode and prefer immutable solution (without setters):
public class Pair {
private String key;
private Integer value;
public Pair(String key, Integer value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public Integer getValue() {
return value;
}
// autogenerated
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
return true;
}
#Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
Usage:
List<Pair> list = new ArrayList<Pair>();
list.add(new Pair("string", 123));
Note: in other languages there are build-in solutions for it like case-classes and tuples in Scala.
Create a Row class that holds the data.
package com.stackoverflow;
import java.util.ArrayList;
import java.util.List;
/**
* #author maba, 2012-10-10
*/
public class Row {
private int intValue;
private String stringValue;
public Row(String stringValue, int intValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public String getStringValue() {
return stringValue;
}
public static void main(String[] args) {
List<Row> rows = new ArrayList<Row>();
rows.add(new Row("string", 123));
}
}
You can create very simple object, like :
public class Row{
private String strVal;
private Integer intVal;
public Row(String s, Integer i){
strVal = s;
intVal = i;
}
//getters and setters
}
Then use it as follows :
ArrayList<Row> myArray = new ArrayList<Row>();
myArray.add(new Row("string", 123));
Map is the option if you are sure that any one value among integer or string is unique. Then you can put that unique value as a key. If it is not true for your case, creating a simple POJO is best option for you. Infact, if in future, there a chance to come more values (columns) per row then also using a POJO will be less time consuming. You can define POJO like;
public class Data {
private int intValue;
private String strValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int newInt) {
this.intValue = newInt;
}
public String getStrValue() {
return strValue;
}
public void setStrValue(String newStr) {
this.strValue = newStr;
}
And in the class you can use it like;
ArrayList<Data> dataList = new ArrayList<Data>();
Data data = new Data();
data.setIntValue(123);
data.setStrValue("string");
dataList.add(data);
You should create a class (e.g. Foo) that contains an int and a String.
Then you can create an ArrayList of Foo objects.
List<Foo> fooList = new ArrayList<Foo>();
This is called a map my friend. It is similar to a dictionary in .net
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
HashMap my be the class you are looking for assuming "string" going to different for different values. Here is documentation on HashMap
Example:
HashMap<String, Integer> tempMap = new HashMap<String, Integer>();
tempMap.put("string", 124);
If you need to add more than one value, you may create HashMap<String, ArrayList> like that.
you can use google collection library Guava there is a Map called Multimap. It is collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
Use Map to solve this problem:
Map<String, Integer> map = new HashMap<String, Integer>();
Eg:
map.put("string", 123);
I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?
i can simply concatenate the two strings , but im sure there is a better way to do this.
You could have a custom object containing the two strings:
class StringKey {
private String str1;
private String str2;
}
Problem is, you need to determine the equality test and the hash code for two such objects.
Equality could be the match on both strings and the hashcode could be the hashcode of the concatenated members (this is debatable):
class StringKey {
private String str1;
private String str2;
#Override
public boolean equals(Object obj) {
if(obj != null && obj instanceof StringKey) {
StringKey s = (StringKey)obj;
return str1.equals(s.str1) && str2.equals(s.str2);
}
return false;
}
#Override
public int hashCode() {
return (str1 + str2).hashCode();
}
}
You don't need to reinvent the wheel. Simply use the Guava's HashBasedTable<R,C,V> implementation of Table<R,C,V> interface, for your need. Here is an example
Table<String, String, Integer> table = HashBasedTable.create();
table.put("key-1", "lock-1", 50);
table.put("lock-1", "key-1", 100);
System.out.println(table.get("key-1", "lock-1")); //prints 50
System.out.println(table.get("lock-1", "key-1")); //prints 100
table.put("key-1", "lock-1", 150); //replaces 50 with 150
public int hashCode() {
return (str1 + str2).hashCode();
}
This seems to be a terrible way to generate the hashCode: Creating a new string instance every time the hash code is computed is terrible! (Even generating the string instance once and caching the result is poor practice.)
There are a lot of suggestions here:
How do I calculate a good hash code for a list of strings?
public int hashCode() {
final int prime = 31;
int result = 1;
for ( String s : strings ) {
result = result * prime + s.hashCode();
}
return result;
}
For a pair of strings, that becomes:
return string1.hashCode() * 31 + string2.hashCode();
That is a very basic implementation. Lots of advice through the link to suggest better tuned strategies.
Why not create a (say) Pair object, which contains the two strings as members, and then use this as the key ?
e.g.
public class Pair {
private final String str1;
private final String str2;
// this object should be immutable to reliably perform subsequent lookups
}
Don't forget about equals() and hashCode(). See this blog entry for more on HashMaps and keys, including a background on the immutability requirements. If your key isn't immutable, then you can change its components and a subsequent lookup will fail to locate it (this is why immutable objects such as String are good candidates for a key)
You're right that concatenation isn't ideal. For some circumstances it'll work, but it's often an unreliable and fragile solution (e.g. is AB/C a different key from A/BC ?).
I have a similar case. All I do is concatenate the two strings separated by a tilde ( ~ ).
So when the client calls the service function to get the object from the map, it looks like this:
MyObject getMyObject(String key1, String key2) {
String cacheKey = key1 + "~" + key2;
return map.get(cachekey);
}
It is simple, but it works.
I see that many people use nested maps. That is, to map Key1 -> Key2 -> Value (I use the computer science/ aka haskell curring notation for (Key1 x Key2) -> Value mapping which has two arguments and produces a value), you first supply the first key -- this returns you a (partial) map Key2 -> Value, which you unfold in the next step.
For instance,
Map<File, Map<Integer, String>> table = new HashMap(); // maps (File, Int) -> Distance
add(k1, k2, value) {
table2 = table1.get(k1);
if (table2 == null) table2 = table1.add(k1, new HashMap())
table2.add(k2, value)
}
get(k1, k2) {
table2 = table1.get(k1);
return table2.get(k2)
}
I am not sure that it is better or not than the plain composite key construction. You may comment on that.
Reading about the spaguetti/cactus stack I came up with a variant which may serve for this purpose, including the possibility of mapping your keys in any order so that map.lookup("a","b") and map.lookup("b","a") returns the same element. It also works with any number of keys not just two.
I use it as a stack for experimenting with dataflow programming but here is a quick and dirty version which works as a multi key map (it should be improved: Sets instead of arrays should be used to avoid looking up duplicated ocurrences of a key)
public class MultiKeyMap <K,E> {
class Mapping {
E element;
int numKeys;
public Mapping(E element,int numKeys){
this.element = element;
this.numKeys = numKeys;
}
}
class KeySlot{
Mapping parent;
public KeySlot(Mapping mapping) {
parent = mapping;
}
}
class KeySlotList extends LinkedList<KeySlot>{}
class MultiMap extends HashMap<K,KeySlotList>{}
class MappingTrackMap extends HashMap<Mapping,Integer>{}
MultiMap map = new MultiMap();
public void put(E element, K ...keys){
Mapping mapping = new Mapping(element,keys.length);
for(int i=0;i<keys.length;i++){
KeySlot k = new KeySlot(mapping);
KeySlotList l = map.get(keys[i]);
if(l==null){
l = new KeySlotList();
map.put(keys[i], l);
}
l.add(k);
}
}
public E lookup(K ...keys){
MappingTrackMap tmp = new MappingTrackMap();
for(K key:keys){
KeySlotList l = map.get(key);
if(l==null)return null;
for(KeySlot keySlot:l){
Mapping parent = keySlot.parent;
Integer count = tmp.get(parent);
if(parent.numKeys!=keys.length)continue;
if(count == null){
count = parent.numKeys-1;
}else{
count--;
}
if(count == 0){
return parent.element;
}else{
tmp.put(parent, count);
}
}
}
return null;
}
public static void main(String[] args) {
MultiKeyMap<String,String> m = new MultiKeyMap<String,String>();
m.put("brazil", "yellow", "green");
m.put("canada", "red", "white");
m.put("USA", "red" ,"white" ,"blue");
m.put("argentina", "white","blue");
System.out.println(m.lookup("red","white")); // canada
System.out.println(m.lookup("white","red")); // canada
System.out.println(m.lookup("white","red","blue")); // USA
}
}
public static String fakeMapKey(final String... arrayKey) {
String[] keys = arrayKey;
if (keys == null || keys.length == 0)
return null;
if (keys.length == 1)
return keys[0];
String key = "";
for (int i = 0; i < keys.length; i++)
key += "{" + i + "}" + (i == keys.length - 1 ? "" : "{" + keys.length + "}");
keys = Arrays.copyOf(keys, keys.length + 1);
keys[keys.length - 1] = FAKE_KEY_SEPARATOR;
return MessageFormat.format(key, (Object[]) keys);}
public static string FAKE_KEY_SEPARATOR = "~";
INPUT:
fakeMapKey("keyPart1","keyPart2","keyPart3");
OUTPUT: keyPart1~keyPart2~keyPart3
I’d like to mention two options that I don’t think were covered in the other answers. Whether they are good for your purpose you will have to decide yourself.
Map<String, Map<String, YourObject>>
You may use a map of maps, using string 1 as key in the outer map and string 2 as key in each inner map.
I do not think it’s a very nice solution syntax-wise, but it’s simple and I have seen it used in some places. It’s also supposed to be efficient in time and memory, while this shouldn’t be the main reason in 99 % of cases. What I don’t like about it is that we’ve lost the explicit information about the type of the key: it’s only inferred from the code that the effective key is two strings, it’s not clear to read.
Map<YourObject, YourObject>
This is for a special case. I have had this situation more than once, so it’s not more special than that. If your objects contain the two strings used as key and it makes sense to define object equality based on the two, then define equals and hashCode in accordance and use the object as both key and value.
One would have wished to use a Set rather than a Map in this case, but a Java HashSet doesn’t provide any method to retrieve an object form a set based on an equal object. So we do need the map.
One liability is that you need to create a new object in order to do lookup. This goes for the solutions in many of the other answers too.
Link
Jerónimo López: Composite key in HashMaps on the efficiency of the map of maps.
I need a sorted set of objects and am currently using the TreeSet. My problem is that the compareTo of the objects will often return 0, meaning the order of those two objects is to be left unchanged. TreeMap (used by TreeSet by default) will then regard them as the same object, which is not true.
What alternative to TreeMap can I use?
Use case: I have a set of displayable objects. I want to sort them by Y coordinate, so that they are rendered in the correct order. Of course, two objects may well have the same Y coordinate.
You're defining one criteria to compare, but you need to add extra criteria.
You say:
I have a set of displayable objects. I want to sort them by Y coordinate, so that they are rendered in the correct order. Of course, two objects may well have the same Y coordinate.
So, If two elements have the same Y coordinate, what you you put first? What would be the other criteria?
It may be the creation time, it may be the x coordinate, you just have to define it:
Map<String,Thing> map = new TreeMap<String,Thing>(new Comparator<Thing>(){
public int compare( Thing one, Thing two ) {
int result = one.y - two.y;
if( result == 0 ) { // same y coordinate use another criteria
result = one.x - two.x;
if( result == 0 ) { //still the same? Try another criteria ( maybe creation time
return one.creationTime - two.creationTime
}
}
return result;
}
});
You have to define when one Thing is higher / lower / equal / than other Thing . If one of the attributes is the same as other, probably you should not move them. If is there other attribute to compare the use it.
The issue you're running into is that compareTo returning 0 means that the objects are equal. At the same time, you're putting them into a set, which does not allow multiple copies of equal elements.
Either re-write your compareTo so that unequal elements return different values, or use something like a java.util.PriorityQueue which allows multiple copies of equal elements.
I've done this before. It's an ordered multi-map and it is just a TreeMap of List objects. Like this..
Map<KeyType, List<ValueType>> mmap = new TreeMap<KeyType, List<ValueType>>();
You need to construct a new LinkedList every time a new key is introduced, so it might be helpful to wrap it in a custom container class. I'll try to find something.
So, I threw this custom container together quickly (completely untested), but it might be what you are looking for. Keep in mind that you should only use this type of container if you are truly looking for an ordered map of value lists. If there is some natural order to your values, you should use a TreeSet as others have suggested.
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MTreeMap<K, V> {
private final Map<K, List<V>> mmap = new TreeMap<K, List<V>>();
private int size = 0;
public MTreeMap() {
}
public void clear() {
mmap.clear();
size=0;
}
public boolean containsKey(K key) {
return mmap.containsKey(key);
}
public List<V> get(K key) {
return mmap.get(key);
}
public boolean isEmpty() {
return mmap.isEmpty();
}
public Set<K> keySet() {
return mmap.keySet();
}
public Collection<List<V>> valueLists() {
return mmap.values();
}
public void put(K key, V value) {
List<V> vlist = mmap.get(key);
if (null==vlist) {
vlist = new LinkedList<V>();
mmap.put(key, vlist);
}
vlist.add(value);
++size;
}
public List<V> remove(Object key) {
List<V> vlist = mmap.remove(key);
if (null!=vlist) {
size = size - vlist.size() ;
}
return vlist;
}
public int size() {
return size;
}
public String toString() {
return mmap.toString();
}
}
Here's a rudimentary test:
public class TestAnything {
public static void main(String[] args) {
MTreeMap<Integer, String> mmap = new MTreeMap<Integer, String>();
mmap.put(1, "Value1");
mmap.put(2, "Value2");
mmap.put(3, "Value3");
mmap.put(1, "Value4");
mmap.put(3, "Value5");
mmap.put(2, "Value6");
mmap.put(2, "Value7");
System.out.println("size (1) = " + mmap.get(1).size());
System.out.println("size (2) = " + mmap.get(2).size());
System.out.println("size (3) = " + mmap.get(3).size());
System.out.println("Total size = " + mmap.size());
System.out.println(mmap);
}
}
The output is this:
size (1) = 2
size (2) = 3
size (3) = 2
Total size = 7
{1=[Value1, Value4], 2=[Value2, Value6, Value7], 3=[Value3, Value5]}
I have one idea of my own, but it's more of a workaround
int compare(Object a, Object b) {
an = a.seq + (a.sortkey << 16); // allowing for 65k items in the set
bn = b.seq + (a.sortKey << 16);
return an - bn; // can never remember whether it's supposed to be this or b - a.
}
sortKey = what really matters for the sorting, for example an Y coordinate
seq = a sequence number assigned to objects when added to the set
There are 2 important things to remember when using sorted sets (e.g. TreeSet) :
1) They are sets; two equal elements are not allowed in the same collection
2) Equality must be consistent with the comparison mechanism (either comparator or comparable)
Therefore, in your case you should "break ties" by adding some secondary ordering criteria. For example: first use Y axis, then X, and then some unique object identifier.
See also http://eyalsch.wordpress.com/2009/11/23/comparators/
What I need is a collection which allows multiple keys to access a single object.
I need to apply frequent alterations to this object.
It also must be efficient for 500k+ entries.
Any implementation of java.util.Map<K,V> will do this - there is no restriction on how many times a particular value can be added under separate keys:
Map<String,Integer> m = new HashMap<String, Integer>();
m.put("Hello", 5);
m.put("World", 5);
System.out.println(m); // { Hello->5, World->5 }
If you want a map where a single key is associated with multiple values, this is called a multi-map and you can get one from the google java collections API or from Apache's commons-collections
I sort of interpreted his request differently. What if one wants two completely different keysets to access the same underlying values. For example:
"Hello" ------|
|----> firstObject
3 ------|
"Monkey" ------|
|----> secondObject
72 ------|
14 -----------> thirdObject
"Baseball" ------|
|----> fourthObject
18 ------|
Obviously having two maps, one for the integer keys and one for the String keys, isn't going to work, since an update in one map won't reflect in the other map. Supposing you modified the Map<String,Object>, updating "Monkey" to map to fifthObject. The result of this modification is to change the Entry<String,Object> within that map, but this of course has no effect on the other map. So whilst what you intended was:
"Monkey" ------|
|----> fifthObject
72 ------|
what you'd get in reality would be this:
"Monkey" -----------> fifthObject
72 -----------> secondObject
what I do in this situation is to have the two side by side maps, but instead of making them say Map<String, Integer> I would make them Map<String, Integer[]>, where the associated array is a single member array. The first time I associate a key with a value, if no array exists yet and the key returns null, I create the array, and associate any other key I wish to with it (in that key's map). Subsequently, I only modify the array's contents, but never the reference to the array itself, and this works a charm.
"Monkey" -------> fifthObjectArray ------|
|-----> fifthObjectArray[0]
72 -------> fifthObjectArray ------|
Uhm…
Map map = new HashMap();
Object someValue = new Object();
map.put(new Object(), someValue);
map.put(new Object(), someValue);
Now the map contains the same value twice, accessible via different keys. If that’s not what you’re looking for you should rework your question. :)
this may do what you want:
import java.util.*;
class Value {
public String toString() {
return x.toString();
}
Integer x=0;
}
public class Main {
public static void main(String[] arguments) {
Map m=new HashMap();
final Value v=new Value();
m.put(1,v);
m.put(2,v);
System.out.println(m.get(1));
System.out.println(m.get(2));
v.x=42;
System.out.println(m.get(1));
System.out.println(m.get(2));
}
Your Question actually got me thinking of making this class to handle such a thing. I am currently working on a 2D game engine and your question completely made me think of exactly what I needed.
By the way you've worded it, I believe what you want is;
An object that holds keys and values, but you can also get the common keys values hold (I use this object specifically to cut down on cpu at the cost of using just a little more memory.)
This Class' The K type is the Primary Key type. The T type is the HashSet Value Type.
The way you implement and use this object is:
MapValueSet<ObjectType1,ObjectType2> mainmap = new
MapValueSet<ObjectType1,ObjectType2>()
HashSet<Integer> tags = new HashSet<Integer>();
public void test(){
ObjectType1 = new ObjectType1();
ObjectType2 = new ObjectType2();
tags.add(mainmap.put(ObjectType1,ObjectType2);
mainmap.get(ObjectType1,Integer);
}
You will need to hold the unique tags in a set or arraylist in any class you implement this because if you didn't you'd be storing entities and not know which one was which. So store the integer you get from the put() method into an arraylist or set, and iterate through that.
You can check this Class's values if they exist, or which key objects the value is set to.
Here is the Class MapValueSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class MapValueSet<K,T> {
Indexer indxK = new Indexer();
Indexer indxT = new Indexer();
Map<K,Integer> kTags = new HashMap<K,Integer>();
Map<T,Integer> tTags = new HashMap<T,Integer>();
Map<Integer,HashSet<Integer>> MapK = new HashMap<Integer,HashSet<Integer>>();
Map<Integer,HashSet<Integer>> MapT = new HashMap<Integer,HashSet<Integer>>();
public int put(K k, T t){
int tag = -1;
if(!kTags.containsKey(k)){
kTags.put(k, indxK.getNextTag());
}
if(!MapK.containsKey(kTags.get(k))){
MapK.put(kTags.get(k), new HashSet<Integer>());
}
if(!tTags.containsKey(t)){
tTags.put(t, tag = indxT.getNextTag());
}
if(!MapT.containsKey(tTags.get(t))){
MapT.put(tag = tTags.get(t), new HashSet<Integer>());
}
MapK.get(kTags.get(k)).add(tTags.get(t));
MapT.get(tag = tTags.get(t)).add(kTags.get(k));
return tag;
}
#SuppressWarnings("unchecked")
public T get(K k, int tag){
Object[] tArr = tTags.keySet().toArray();
for(int i = 0; i < tArr.length; i++){
if(tTags.get((T)tArr[i])== tag){
return (T)tArr[i];
}
}
return null;
}
public boolean removeAtKey(K k, T t){
int kTag = -1;
int tTag = -1;
if(kTags.get(k) != null){
kTag = kTags.get(k);
}
if(tTags.get(t) != null){
tTag = tTags.get(t);
}
if(kTag == -1 || tTag == -1){
System.out.println("Keys are Blank at: removeAtKey(k,t)");
return false;
}
boolean removed = false;
if(MapK.get(kTag) != null){
removed = MapK.get(kTag).remove(tTag);
}
if(MapT.get(tTag) != null){
MapT.get(tTag).remove(kTag);
}
if(!MapK.containsKey(kTag)){
kTags.remove(k);
indxK.removeTag(kTag);
}
if(MapK.containsKey(kTag)){
tTags.remove(t);
indxT.removeTag(tTag);
}
return removed;
}
public void removeAtValue(T t){
if(!tTags.containsKey(t)){
return;
}
Object[] keyArr = MapT.get(tTags.get(t)).toArray();
for(int i = 0; i < keyArr.length; i++){
MapK.get(keyArr[i]).remove(tTags.get(t));
}
indxT.removeTag(tTags.get(t));
MapT.remove(tTags.get(t));
tTags.remove(t);
}
public boolean mapContains(T t){
if(tTags.get(t) == null){
return false;
}
int tTag = tTags.get(t);
return MapT.get(tTag) != null && !MapT.get(tTag).isEmpty();
}
public boolean containsKey(K k){
if(kTags.get(k) == null){
return false;
}
return MapK.containsKey(kTags.get(k));
}
public boolean keyContains(K k, T t){
if(kTags.get(k) != null && tTags.get(t) != null){
return MapK.get(kTags.get(k)).contains(tTags.get(t));
}
return false;
}
#Override
public String toString(){
String s = "";
s = s+ "Key Map: " + MapK.toString() + "\n";
s = s+ "Value Map: " + MapT.toString() + "\n";
s = s+ "KeyTag Map: " + kTags.toString() + "\n";
s = s+ "ValueTag Map: " + tTags.toString() + "\n";
s = s+ "KeyTag List: " + indxK.activeSet().toString() + "\n";
s = s+ "ValueTag List: " + indxT.activeSet().toString();
return s;
}
}