I have a HashMap like this  LinkedHashMap&lt;K, V&gt; = new LinkedHashMap&lt;&gt;();   this map is used as cache to implement LRU (least recently used) In this cache I want to save results from functions that have no &quot;side-effect&quot; so for the same input they will always produce the same output. Im also using Bi-Functions that have &lt;T,U,R&gt; T and U are generic types. Here comes the Pair&lt;T,U&gt; into play. How do I save a Pair like this as a key into my Hash-Map? And can someone explain how exactly the overwriting of the equals(Obj o) and hashCode() function is supposed to help with this problem?
99253
I like how Java has a Map where you can define the types of each entry in the map, for example &lt;String, Integer&gt;.   What I'm looking for is a type of collection where each element in the collection is a pair of values.  Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.    The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).    Essentially I want to be able to define an ARRAY of type &lt;String,Integer&gt; or any other 2 types.    I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.    I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.    I only need to store pairs in the collection, so I only need two values per entry.  Does something like this exist without going the class route?  Thanks!
3552
According to the documentation of the == operator in ,      For predefined value types, the   equality operator (==) returns true if   the values of its operands are equal,   false otherwise. For reference types   other than string, == returns true if   its two operands refer to the same   object. For the string type, ==   compares the values of the strings.   User-defined value types can overload   the == operator (see operator). So can   user-defined reference types, although   by default == behaves as described   above for both predefined and   user-defined reference types.   So why does this code snippet fail to compile?  bool Compare&lt;T&gt;(T x, T y) { return x == y; }   I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the == operator is predefined for all types?  Edit: Thanks, everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct.  But, in case I'm using a reference type, would the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?  Edit 2: Through trial and error, we learned that the == operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true, even when Test.test&lt;B&gt;(new B(), new B()) is called:  class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test&lt;T&gt;(T a, T b) where T : A { Console.WriteLine(a == b); } }
46281
In Dan Appleman's book Advanced Apex Programming, he explains how using SObjects as Map keys (i.e. Map&lt;SObject, *value*&gt;) is supported but it's poor practice, since the key is actually determined by a hash of all the fields on that SObject key - so if there's a change to even just one field, the key is changed.   My question is - why is this supported? I'm having trouble thinking of even one case where using this type of collection would be desired? The point of using a Map is to be able to retrieve data based on semantic-trivial, immutable data (such as IDs)...
53155
Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?  For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
1054
I am relatively new to Java, and often find that I need to sort a Map&lt;Key, Value&gt; on the values.  Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key.  Is there an easier way?
83393
A  is a function $H : A \to B$ between two sets with some algebraic structure $(A, *)$ and $(B, \star)$ such that   $H$ is collision resistant, i.e. it is hard to find $x \neq y$ such that $H(x) = H(y)$ and $H$ is a homomorphism, i.e. $H(x * y) = H(x) \star H(y)$.   Are there any practical realizations of such a homomorphic hash function, or even a homomorphic signature scheme (i.e., where we can "add" valid signatures to get a signature of the "sum" of two messages)?  Even better, are there even any libraries implementing this?
27628
How would you initialise a static Map in Java?  Method one: static initialiser  Method two: instance initialiser (anonymous subclass) or some other method?  What are the pros and cons of each?  Here is an example illustrating the two methods:  import java.util.HashMap; import java.util.Map;  public class Test {     private static final Map&lt;Integer, String&gt; myMap = new HashMap&lt;&gt;();     static {         myMap.put(1, "one");         myMap.put(2, "two");     }      private static final Map&lt;Integer, String&gt; myMap2 = new HashMap&lt;&gt;(){         {             put(1, "one");             put(2, "two");         }     }; }
43510
In the following code I loop through a map and test if an element needs to be erased.  Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?  map&lt;string, SerialdMsg::SerialFunction_t&gt;::iterator pm_it; for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++) {     if (pm_it-&gt;second == delete_this_id) {         port_map.erase(pm_it-&gt;first);     } }   UPDATE: Of course, I then  which I didn't think would be related but answers my question.
25516
I have heard that the Java implementation of Generics is not as good as the C# implementation. In that the syntax looks similar, what is it that is substandard about the Java implementation, or is it a religious point of view?
18943
I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:  import org.apache.commons.lang.builder.EqualsBuilder;  public class Foo {     public class Bar {         private Bar() {}          public Foo getMyFoo() {             return Foo.this         }          private int myInt = 0;          public boolean equals(Object o) {             if (o == null || o.getClass() != getClass) return false;              Bar other = (Bar) o;             return new EqualsBuilder()                 .append(getMyFoo(), other.getMyFoo())                 .append(myInt, other.myInt)                 .isEquals();         }     }      public Bar createBar(...) {         //sensible implementation     }      public Bar createOtherBar(...) {         //another implementation     }      public boolean equals(Object o) {         //sensible equals implementation     } }   Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?
52986
I am trying to add map of map values, I have to intialize the map key first and then try to add value later. Below is the exact logic i am trying to achieve.  Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt; finalMap = new Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt;();  Map&lt;string,List&lt;string&gt;&gt; subMap = new Map&lt;string,List&lt;string&gt;&gt;(); submap.put('One',new list&lt;string&gt;{'One','TWO'});  finalMap.put('SUB1',new Map&lt;string,List&lt;string&gt;&gt;());  //Do some logics and finally try to add the values with the key  finalmap.get('SUB1').put(subMap); //Error as stated below  System.debug(finalmap);      ERROR :Method does not exist or incorrect signature:   [Map&lt;String,List&lt;String&gt;&gt;].put(Map&lt;String,List&lt;String&gt;&gt;)
101459
I'm doing some polymorphic programming, and I decided that I wanted to be able to gracefully handle partial saves using SaveResult without blocking the user experience. The code looks roughly like this:  static void logDmlErrors(SObject[] src, SObject[] dest, SaveResult[] results, String message) {     // Transform results into Chatter error messages, send them to admins }   I then went about writing the utility methods that would use this function:  public static void insertRecords(SObject[] src, SObject[] dest, String message) {     logDmlErrors(src, dest, Database.insert(dest, false), message); }   Everything went well, until I came across the delete and undelete methods, which instead use DeleteResult and UndeleteResult. Both of those two classes contain the exact same methods as SaveResult, and yet don't appear to inherit from a common ancestor. This means that I can't just cast to a super-type to get to this information.  Thankfully, Summer 16 apparently introduced support for serializing (and deserializing) these classes as JSON, so I do have a fairly expensive (but accurate) workaround if I want proper polymorphic behavior, but I thought I'd throw it out there and see if someone has an alternative solution to this problem.
29117
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.  First I tried this example in the console:  a = b = {}; a.foo = 'bar'; console.log(b.foo);   The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.  a = b = 'foo'; a = 'bar'; console.log(b);   That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.  Why does this happen?  N.B. This example could be simplified even more with the following code:    a = {}; b = a; a.foo = 'bar'; console.log(b.foo);  a = 'foo'; b = a; a = 'bar'; console.log(b);     (I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
14530
Is there any utility for deep cloning for java collections:   Arrays Lists Maps   NOTE: prefer some solution without usage of serialization, but with use of Object.clone() method. I can be sure that my custom object will implement clone() method and will use only java-standard classes that are cloneable...
34544
I was wondering if there is a cryptographic hash where the resulting hash is identical to the input for the hash function.  If this is the case, would it be a weakness in the hashing function?
14108
Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,  set[obj] = true;   This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?