您好我试图通过使用普通数组存储 2 个键值来避免创建对象,但它似乎不起作用。
我可以知道是否有任何解决方案可以避免创建一个对象,或者我只是太努力了?
忘记添加:
1)我知道为什么它不起作用......如果我不这样做,我将不会为 key 实现 equals() 和 hashcode()。
2)基本上我试图在检索密钥时避免创建 1 个对象。通常在服务类中会有一个方法
public void get(String key1, String key2){
return keyMap.get(new Key(key1,key2)); <>>avoiding the new Key()
}
断线
import java.util.HashMap;
import java.util.Map;
public class ArrayMap {
/**
* @param args
*/
public static void main(String[] args) {
/*start A Possible to get this to work? */
Map<String[], String> arrMap = new HashMap<>();
arrMap.put(new String[] { "hello", "hi" }, "hello motto");
System.out.println(arrMap);
System.out.println(arrMap.get(new String[] { "hello", "hi" })); // print
// null
/* end of A */
/*Start of B: Reason: to avoid this */
Map<Key, String> keyMap = new HashMap<Key, String>();
keyMap.put(new Key("hello", "hi"), "hello motto"); // I wish to avoid one object creation
System.out.println(keyMap.get(new Key("hello", "hi"))); // print
// "hello motto"
/*End of B: Reason: to avoid this */
}
}
class Key {
private final String key1;
private final String key2;
public Key(String key1, String key2) {
this.key1 = key1;
this.key2 = key2;
}
public String getKey1() {
return key1;
}
public String getKey2() {
return key2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key1 == null) ? 0 : key1.hashCode());
result = prime * result + ((key2 == null) ? 0 : key2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Key other = (Key) obj;
if (key1 == null) {
if (other.key1 != null)
return false;
} else if (!key1.equals(other.key1))
return false;
if (key2 == null) {
if (other.key2 != null)
return false;
} else if (!key2.equals(other.key2))
return false;
return true;
}
}