I know that implementing/overriding equals() without also overriding hashCode() violates the equals/hashCode contract.  But what if a class implements only hashCode() and not equals()?
7577
What issues / pitfalls must be considered when overriding equals and hashCode?
79065
I'm trying to figure out which of these interfaces I need to implement. They both essentially do the same thing. When would I use one over the other?
37448
What is the difference between a Hash Map and dictionary ADT. And when to prefer one over another. For my programming assignment my instructor has asked to use one of them but I don't see any difference in between both. The program is supposed to work with a huge no. of strings. Any suggestions?
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?
124250
I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...  I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the composites hash map. I was able to get around this by calling to_owned on the vector. Is this the right way to handle this?  I also see that when I build the code, I get warnings about unused code for warning: struct is never constructed: 'Sieve' and warning: method is never used: 'new', am I constructing them incorrectly?  use std::collections::HashMap;  struct Sieve {     composites: HashMap&lt;u64, Vec&lt;u64&gt;&gt;,     x: u64, }  impl Sieve {     fn new() -&gt; Sieve {         Sieve {             composites: HashMap::new(),             x: 2,         }     } }  impl Iterator for Sieve {     type Item = u64;      fn next(&amp;mut self) -&gt; Option&lt;u64&gt; {         let x = self.x;         self.x = self.x + 1;         match self.composites.get(&amp;x) {             Some(numbers) =&gt; {                 for _num in numbers.to_owned() {                     self.composites                         .entry(x + _num)                         .and_modify(|v| v.push(_num))                         .or_insert(vec![_num]);                 }                 self.composites.remove(&amp;x);                 self.next()             }             None =&gt; {                 self.composites.insert(x * x, vec![x]);                 Some(x)             }         }     } }  fn main() {     let mut sieve = Sieve::new();      println!("{:?}", sieve.next()); // 2     println!("{:?}", sieve.next()); // 3     println!("{:?}", sieve.next()); // 5     println!("{:?}", sieve.next()); // 7 }   .  I , this made it difficult to get feedback on. I have refactored the code to use iterators
40162
Please demonstrate how the ternary operator works with a regular if/else block. Example:  Boolean isValueBig = value &gt; 100 ? true : false;     Exact Duplicate:
14775
There is a case where a map will be constructed, and once it is initialized, it will never be modified again.  It will however, be accessed (via get(key) only) from multiple threads.  Is it safe to use a java.util.HashMap in this way?  (Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice.  Hence, this question is not "Which one should I use?" nor is it a performance question.  Rather, the question is "Would it be safe?")
98914
The MSDN documentation on  describes 3 contradicting rules for how the method should work.     If two objects of the same type represent the same value, the hash function must return the same constant value for either object. For the best performance, a hash function must generate a random distribution for all input. The hash function must return exactly the same value regardless of any changes that are made to the object.   Rules 1 &amp; 3 are contradictory to me.  Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.
282
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version. Is there a simpler way than: List&lt;String&gt; newList = new ArrayList&lt;String&gt;(); newList.addAll(listOne); newList.addAll(listTwo);
67360
Edit:    From another question I provided an answer that has links to a lot of questions/answers about singletons:   So I have read the thread  And the argument still rages.  I see Singletons as a Design Pattern (good and bad). The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).  So the main questions that need to be answered are:   When should you use a Singleton How do you implement a Singleton correctly   My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.  So get the ball rolling: I will hold my hand up and say this is what I use but probably has problems. I like "Scott Myers" handling of the subject in his books "Effective C++"     Good Situations to use Singletons (not many):         Logging frameworks   Thread recycling pools      /*  * C++ Singleton  * Limitation: Single Threaded Design  * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf  *      For problems associated with locking in multi threaded applications  *  * Limitation:  * If you use this Singleton (A) within a destructor of another Singleton (B)  * This Singleton (A) must be fully constructed before the constructor of (B)  * is called.  */ class MySingleton {     private:         // Private Constructor         MySingleton();         // Stop the compiler generating methods of copy the object         MySingleton(MySingleton const&amp; copy);            // Not Implemented         MySingleton&amp; operator=(MySingleton const&amp; copy); // Not Implemented      public:         static MySingleton&amp; getInstance()         {             // The only instance             // Guaranteed to be lazy initialized             // Guaranteed that it will be destroyed correctly             static MySingleton instance;             return instance;         } };   OK. Lets get some criticism and other implementations together. :-)
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
1079
What are the best practices for using Java's @Override annotation and why?     It seems like it would be overkill to mark every single overridden method with the @Override annotation.   Are there certain programming situations that call for using the @Override and others that should never use the @Override?
3469
I came across this recently, up until now I have been happily overriding the equality operator (==) and/or Equals method in order to see if two references types actually contained the same data (i.e. two different instances that look the same). I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned). While looking over some of the  I came across an  that advises against it. Now I understand why the article is saying this (because they are not the same instance) but it does not answer the question:  What is the best way to compare two reference types? Should we implement ? (I have also seen mention that this should be reserved for value types only). Is there some interface I don't know about? Should we just roll our own?!  Many Thanks ^_^ Update Looks like I had mis-read some of the documentation (it's been a long day) and overriding  may be the way to go..  If you are implementing reference types, you should consider overriding the Equals method on a reference type if your type looks like a base type such as a Point, String, BigNumber, and so on. Most reference types should not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you should override the equality operator.
115421
In this simplified example I have a generic class, and a method that returns a Map regardless of the type parameter.  Why does the compiler wipe out the types on the map when I don't specify a type on the containing class?  import java.util.Map;  public class MyClass&lt;T&gt; {     public Map&lt;String, String&gt; getMap()     {            return null;     }      public void test()     {            MyClass&lt;Object&gt; success = new MyClass&lt;Object&gt;();         String s = success.getMap().get("");          MyClass unchecked = new MyClass();         Map&lt;String, String&gt; map = unchecked.getMap();  // Unchecked warning, why?         String s2 = map.get("");          MyClass fail = new MyClass();         String s3 = fail.getMap().get("");  // Compiler error, why?     } }   I get this compiler error.  MyClass.java:20: incompatible types found   : java.lang.Object required: java.lang.String                 String s3 = fail.getMap().get("");  // Compiler error
92088
public class WrapperTest {      public static void main(String[] args) {          Integer i = 100;         Integer j = 100;          if(i == j)             System.out.println("same");         else             System.out.println("not same");     }     }   The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.
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)
32548
Why do HMAC/SHA IV's have a fixed value? I refer to the arbitrary H constants which are included in the algorithm prior to any data being fed in.  Why aren't they exposed to the user, so one can decide on an IV and modify it accordingly (for example, in java they are provided at hash function specification, instead of being supplied by the user at init)?  How does modifying these IVs affect the algorithm?