Java - equals() and hashcode() quagmire

The equals() contract as specified demands an equivalence relation. It demands that the below properties are satisfied.

  • Reflexive - For any non-null reference x, x.equals(x) must return true.
  • Symmetric - For any non-null references x and y, x.equals(y) must return true if and only if y.equals(x) returns true.
  • Transitive - For any non-null references x, y and z, if x.equals(y) returns true and y.equals(x) returns true, then x.equals(z) must also return true.
  • Consistent - for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) must return false.

hashCode() contract demands the below

  • Consistent - Calling the method multiple times must return the same value.
  • If two objects are equal satisfying the equals() contract, they must return the same hash value.

ORM objects

One thing to remember while overriding hashCode() and equals for objects that are used in ORM tools is to not use the primary key variable(usually named id) in hashCode() because the primary key will be set only after the data is persisted. So if we create an object and put the object in a HashSet with id field used in hashCode(), we will never find it in the Set after its persisted.

Also since getters force the loading of lazy loaded objects, its always better to use getter methods rather than accessing the variables directly in both equals() and hashCode() methods.

Inheritance impact for equals() contract

Inheritance throws a wrench in the equals() contract. The question is whether the subclass should override the equals() method because this always break the symmetric contract of the equals().

Using instanceof to identify the method argument in equals() breaks the symmetric contract in case of inheritance. If class B extends class A, then a.equals(b) returns true but b.equals(a) returns false. The check a instanceof B fails. Its better to make the class final if we are going to use instanceof operator.

Another approach is to use getClass() in equals() which will return false in both cases. But using getClass() violates the Liskov Substitution Principle and lead to unexpected behaviors. Depending on run-time classes for equals() method causes subClasses to not be equal to the superClass. Also be careful when using getClass() in Spring and ORM environments because they make heavy use of proxy objects.

These two methods play a big role in the Collections library. When an object is added to a collection, the the hashCode of the provided object is calculated and placed in a bucket mapped to this hashCode. If another object has the same hashCode, it is also added to the same bucket.

Retrieving the object involves the following steps

  • Calculate the hashCode and identify the bucket.
  • Perform a==b comparison to see if the provided object and saved object are the same. If true, return the object from the bucket.
  • If a==b fails, then perform a.equals(b). The comparison looks like a==b || a.equals(b).
  • If this succeeds, return the saved object or return null.

If hashCode() and equals() are not implemented properly satisfying the required contract, the Collection behavior is implementation dependent.


class Obj {
    private final String name;

    public Obj(final String name) { = name;

    public String getName() {
        return name;

    public int hashCode() {
        return 3;

    public boolean equals(Object obj) {
        return false;

    public String toString() {
        return name;

The implementation of equals() and hashCode() are terrible for the above class(only for learning purposes).

Any object of class Obj will return the same hashcode and the equals() method will always fail.

HashMap<Obj, String> map = new HashMap<>();

Obj obj1 = new Obj("p"), 
    obj2 = new Obj("q");

map.put(obj1, "java");
map.put(obj2, "spring");

System.out.println(map.get(new Obj("p")));
System.out.println(map.get(new Obj("q")));


null     // for lineno: 9
java     // for lineno: 10
null     // for lineno: 11
spring   // for lineno: 12

Internally map saves the (key, value) pair as an Map.Entry object. Since the hashcode is same for both obj1 and obj2, there will be 2 entries in the same bucket.

For retrieval,

  • lineno: 9 - a new object is passed to the map as key to retrieve the value. First the hashCode of this key is computed and we check the corresponding bucket. The bucket will have 2 entries. The first entry is picked and the condition a==b || a.equals(b) fails. So null is returned.
  • lineno: 10 - object used as key earlier is passed to the map to retrieve the value. First the hashCode of this key is computed and we check the corresponding bucket. The bucket will have 2 entries. The first entry is picked and the first half of the condition a==b || a.equals(b) succeeds. We get the correct value.

So while getting from a map, the entries in that particular bucket are picked and the key for each entry is compared against the obj passed in the map.get(). If any succeeds, the value of that entry is returned.

In the above code, consider that the equals() method always returns true. Then the value that we get is implementation dependent. In my machine, I get the last added value ie) spring for all the 4 retrievals.


In short, there is no simple way to properly implement the equals() method. There are different workarounds to resolve these issues. Have a look here and here. They discuss multiple approaches to resolve these issues and the new problems that come with each approach. We need to consider the tradeoffs for each of the different choices.

Quote: Religion and Women

Religion is against women’s rights and women’s freedom. In all societies women are oppressed by religion

Naukri website sucks in Safari

I just created an account in Naukri and its support for safari sucks. When I try to add a language to my personal details section in safari, the webapp adds the same detail multiple times so that the same language is present more than 20 times in my personal details and worst, the ui shows that the request failed in safari.

I am not sure what experimental features these guys are using though but suffice to say whatever they are, they are not needed at all.

I forgot my password and when I tried to reset the same in the website using safari, it sent me around 5 reset password emails and the application locked me out saying exceeded retry attempt. Try after 24 hours my ass.

I had to create a new account since I had not linked the fuckery to the application not working in safari.

Shit works in chrome though. I just spent the last hour fixing naukri’s screwup.

It seems Chrome is the new IE except its so advanced that everything else is broken because nobody tests their UI in anything else.

Drive fast and break everything is the agile way as people have understood it, it seems.

Just do proper regression testing gentlemen.

Quote of the day: Looking at you Javascript

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius – and a lot of courage – to move in the opposite direction.

Albert Einstein

How human eyes see colour

Jamie Wong has provided a detailed treatsie on how human eye perceives colour starting from electromagnetic radiation to colour spaces and Gamma correction and so on.

Through an exploration of electromagnetic radiation, optical biology, colorimetry, and display hardware, I hope to start filling in some of these gaps. If you want to skip ahead, here’s the lay of the land we’ll be covering:

I don’t really understand all the maths involved here but it is exhautively detailed. Is that a right turn of phrase? Not sure.

Biases and Perceptions - iPhone Edition

Thom Holwerda over at OSNews

When you’re as deeply enveloped in the Apple bubble as people like Rene Ritchie and John Gruber, reality inside the bubble starts folding in on itself. You sit deep inside your bubble, and when you look outwards, the curves and bends of the bubble’s surface twist and turn reality outside of the bubble into ever more grotesque and malformed versions of it.

Could not have said it better myself

Cynicism and Fear

Caitlin Moran via Brain Pickings

When cynicism becomes the default language, playfulness and invention become impossible. Cynicism scours through a culture like bleach, wiping out millions of small, seedling ideas. Cynicism means your automatic answer becomes “No.” Cynicism means you presume everything will end in disappointment.

And this is, ultimately, why anyone becomes cynical. Because they are scared of disappointment. Because they are scared someone will take advantage of them. Because they are fearful their innocence will be used against them — that when they run around gleefully trying to cram the whole world in their mouth, someone will try to poison them.

She is right on point(emphasis mine). We all start at the same end trusting everyone around us, believing only in good but our experiences moves us along to the far right making the cynic question every motive and look for ways that people can hurt us. The time I spend on this activity is all consuming depriving me of enjoying life. The question is how do you bring someone back.

Stunning Presentation 🤷🏾‍♂️

From Collective Noun via Cultural Offering

What an inspired choice of Powerpoint transitions

Watch the entire presentation at

Jyotirao Phule - Social Activist Mahatma

From Wikipedia:

In 1848, Jyotiba visited the first girl’s school in Ahmadnagar, run by Christian missionaries. It was also in 1848 that Young Jyotiba read Thomas Paine’s book Rights of Man (1791), and developed a keen sense of social justice. He realised that lower castes and women were at a disadvantage in Indian society, and also that education of these sections was vital to their emancipation.

To this end, Jyotirao at the age of 22 first taught reading and writing to his wife, Savitribai, and then the couple started the first indigenously run school for girls in Pune in 1848, for which he was forced to leave his parental home. When they were ostracised by their family and community, their friend Usman Sheikh and his sister Fatima Sheikh provided them their home to stay and helped them to start the very first girl’s school in their premises.

Great Questions...

to ask

Quote: Never waste ...

Boner’s are rare. Don’t waste them.

President Selina Meyer

Flash reaches end of life


But as open standards like HTML5, WebGL and WebAssembly have matured over the past several years, most now provide many of the capabilities and functionalities that plugins pioneered and have become a viable alternative for content on the web. Over time, we’ve seen helper apps evolve to become plugins, and more recently, have seen many of these plugin capabilities get incorporated into open web standards. Today, most browser vendors are integrating capabilities once provided by plugins directly into browsers and deprecating plugins.

Given this progress, and in collaboration with several of our technology partners – including Apple, Facebook, Google, Microsoft and Mozilla – Adobe is planning to end-of-life Flash. Specifically, we will stop updating and distributing the Flash Player at the end of 2020 and encourage content creators to migrate any existing Flash content to these new open formats.

I still remember seeing my friends create animations effortlessly using Flash and being awed by the output. It is sad that all those flash data will be lost for eternity.

I came across this website and it looks like we can open internet archive links here.

Quote: Learn History


“The study of history is a powerful antidote to contemporary arrogance. It is humbling to discover how many of our glib assumptions, which seem to us novel and plausible, have been tested before, not once but many times and in innumerable guises; and discovered to be, at great human cost, wholly false. ”

Paul Johnson

Quote: Pride leads to fall

From Village Undertaker

In disobedience is hidden pride.

In humility is hidden love.

In pride there is no love.

All your unhappiness comes from your pride.

Archbishop Seraphim (Sobolev) of Bogucharsky

Federer won 2017 Wimbledon Open

… and the world watches in awe

பள்ளிகள் என்னும் நரகம்

கீற்று இதழ்:

மதுரையில் பார்ப்பன பாரதி பணியாற்றிய சேதுபதி பள்ளியில் குருபூர்ணிமா அன்று(08/07/2017) ஆர்.எஸ்.எஸ் ஆசிரியர்களின் காலை மாணவர்களை வைத்து வலுக்கட்டாயமாக கழுவ வைத்திருக்கின்றார்கள். மேலும் பள்ளியில் கோ பூசை, கங்கா பூசை போன்றவற்றையும் செய்திருக்கின்றார்கள். எவ்வளவு பார்ப்பனக் கொழுப்பும், பார்ப்பன அடிவருடித்தனமும் இருந்திருந்தால் மாணவர்களை கண்ட பொறுக்கி ஆர்.எஸ்.எஸ் ஆசிரியர்களின் காலை கழுவ வைத்திருப்பார்கள். இவர்களை எல்லாம் ஆசிரியர்கள் என்று விளிப்பதே மிகவும் கேவலமாகும்.

என்ன ஒரு திமிர். இது உண்மையாக இருந்தால் இதைவித கேவலம் எதுவும் இருக்க முடியாது. இங்கே ஆசிரியர் என்று எவரும் கிடையாது. இவை பள்ளிக்கூடங்களும் அல்ல. இப்படி நடந்ததை கேள்விப்பட்டபின்னும் அமைதியாக இருக்கும் பெற்றோரே அனைத்திற்கும் காரணம்.

பிள்ளைகளின் ஆர்வத்தையும், கேள்வி மனப்பான்மையையும் அடியாலும், மிரட்டலாலும் பிள்ளைகள் அந்த நரகத்தில் அவர்களுடைய மானமரியாதையை இழந்து ஒரு மாட்டின் நிலைக்கு கொண்டுவரப்படுகிறார்கள்.

Google paying Academics to write papers which support its business

From Madison Malone Kircher of NewYork Magazine(via Daring Fireball)

Over the last ten years, Google (er, um, Alphabet) has paid thousands of dollars to people in the academic community working on research that directly involves the company’s business, The Wall Street Journal reported earlier Tuesday. Dollar amounts ranged from $5,000 to $400,000, and Google’s financial contributions to the research were often not disclosed in the finished products, the Journal also reported. A former Google employee said the company had assembled a list of research papers, complete with “working titles, abstracts and budgets,” Google wanted to see produced and then used that list to find academics willing to work with them on those projects. Around 100 such papers have been funded by Google since 2009.

Don’t be evil Google, Don’t be evil.

Update 1:

Nick Heer

The Campaign for Accountability’s 35-page report was published yesterday, and it makes many of the same claims as the Journal article — the Journal cites it as a source.

But the Campaign for Accountability is a kind of sketchy firm itself: they have repeatedly refused to disclose their funding sources, as Google’s Leslie Miller pointed out in a post addressing this study. When I contacted them earlier today to ask for information on their donors, Daniel Stevens, their executive director, simply sent me a copy of their response to Miller, accusing her of deflecting. I haven’t heard back from Stevens with anything more substantial or, indeed, less ironic.

Leslie Miller’s response does not outright deny the accusations. The wordings are in such a way that they neither confirm nor deny the accusations.

Nevertheless, we’re proud to maintain strong relations with academics, universities and research institutes, in our own name, so we wanted to take a few moments to respond to the report.

We run many research programs that provide funding and resources to the external research community. This helps public and private institutions pursue research on important topics in computer science, technology, and a wide range of public policy and legal issues. Our support for the principles underlying an open internet is shared by many academics and institutions who have a long history of undertaking research on these topics—across important areas like copyright, patents, and free expression. We provide support to help them undertake further research, and to raise awareness of their ideas.

Also the professor mentioned in the NyMag article forgot the mention the sponsor of his study even though the study’s results benefit Google. Some oversight indeed.

Update 2:

Liam Tung from ZDNet:

“The irony of discussing disclosures and transparency with the Campaign for Accountability is that this group consistently refuses to name its corporate funders. And those backers won’t ‘fess up either,” wrote Miller.

“The one funder the world does know about is Oracle, which is running a well-documented lobbying campaign against us. In its own name and through proxies, Oracle has funded many hundreds of articles, research papers, symposia and reports.

Having Children

They fuck you up, your mum and dad.
They may not mean to, but they do.
They fill you with the faults they had
And add some extra, just for you.

But they were fucked up in their turn
By fools in old-style hats and coats,
Who half the time were soppy-stern
And half at one another’s throats.

Man hands on misery to man.
It deepens like a coastal shelf.
Get out as early as you can,
And don’t have any kids yourself.

Philip Larkin

Sounds about right.

Movie Review - Blue Jasmine (2013)

This is my first Woody Allen movie and I am in love with him. How does Woody Allen write these characters? Is it possible that he met someone like this? Played to perfection by Cate Blanchett, this is one of the best movies I have seen in a long time.

A woman who lived her life as a trophy wife has lost everything and comes to live with her sister while trying to get her life together. She is cruel to her sister, insulting her at every opportunity, insulting everyone around her and yet she simply does not care about it, lost in her own little world. I did not expect the twist at the end but it did not felt cheap or the feeling of betrayal I sometimes get from movies that go for that kind of thing. The ending was brilliantly built and you think, of course that is what will happen and you can’t have it any other way.

I still can’t get the unsympathetic character out of my head. Cate brilliantly portrays it in such a way that rather than being repulsed by her, we are sympathetic to her and try to understand her. Her sister character was also well done.

Even when she tries to scam her way into a marriage to a wealthy guy, you only feel sorry for the character. I don’t know if its the brilliance of the writing or the acting. Anyway a great watch.

Quote: End of the World

The object of education is not to fill a man’s mind with facts;
 it is to teach him how to use his mind in thinking.

Henry Ford

Book Review - What's Yours is Mine

A thoroughly researched book by Nick Heer detailing the various ways which the so called Sharing economies are destroying the very communities that they purport to nurture and develop.

But I do believe it is possible—even essential—to be skeptical about what I think of as Inspirational Technology Tales. When coupled to an agenda with a lot of money behind it, we owe it to ourselves to ask what it is we are being sold.

The book discusses the effect of the slogan “empowering people from the tyranny of bureaucracy” right from New york to Chennai and lists the various ways in which the poor and disadvantaged are exploited by the rich physically and economically.

How these companies distort facts to sell a lie of the paradise that they bring is laid out beautifully in the book. It is a must read to understand the level of destruction these companies are causing to the established norms of community and society. The only reason for the existence of these companies is to line of pockets of the parasitic VCs and people are willing to destroy themselves for the reduced cost in short-term.

Anybody who reads this and are aware of the shit that is going on in places like Uber, Airbnb and yet continue to use those services are nothing but fucking hypocrites. It is very easy to click a like button in Facebook or send a tweet but to actually refuse to use these services is hard because it causes discomfort. So, the world continues to spin.

Quote: Reality as this World perceives it 🐵

Truth is like poetry And most people fucking hate poetry

Overheard over DC bar

Advice with Scars on it

Advice with scars from Execupundit:

1.If something doesn’t feel right, don’t pretend that it is right.

2.Be wary of wit at the expense of others. It has a habit of turning sour.



12.Look, and keep looking, for new ways of looking.

Quote: Gardening is enriching

If you have a garden and a library, you have everything you need

Marcus Tullius Cicero

In Praise Of Idleness

Bertrand Russell1

One of the commonest things to do with savings is to lend them to some Government. In view of the fact that the bulk of the public expenditure of most civilized Governments consists in payment for past wars or preparation for future wars, the man who lends his money to a Government is in the same position as the bad men in Shakespeare who hire murderers. The net result of the man’s economical habits is to increase the armed forces of the State to which he lends his savings. Obviously it would be better if he spent the money, even if he spent it in drink or gambling.

His words have only come truer over time. Are we any better today? There are people who say violence has come down when compared to 500 years or 1000 years ago. But that is a surface argument which does not stand up during close scrutiny. First how do you quantify what is violence exactly? If violence is people killing each other in the name of religion, language, ethnicity, raping women, killing children because they are different, then this kind of direct violence has come down. But as killing has come down, another indirect violence has been on the rise. People nowadays don’t kill each other(which is merciful in a way that you suffer for an hour and then die) but they can make your life a living hell by abusing authority, financially ruin you by effective use of the court system, add unneeded complexity for no rational reason and then introduce a new layer of bureaucracy to manage this complexity, thereby draining you emotionally and financially in the process. Tell me is this also not violence?

At least then, I would know who my enemy was then, look him in the eye when he kills me and know the reason for the violence that happened, however stupid it is. Today, nobody knows what the fuck is happening? We have laws which contradict each other, courts becoming activists, courts which function in secrecy and give preferential treatment to politicians, actors and people they prefer. India will be the only democracy in the world where courts reject the will of the parliament ie) the will of the people. The recent NJAC issue from 2014 is one example. Politicians are no saints but democratically elected representatives have the right to fuck things up as they please within what the constitution allows however bad they may be. It is the burden of the people to take stock and right the sinking ship. The function of the courts is to upload the rule of law, not to make laws. Sadly, the elements in the democracy that should care don’t know anything about it.

The world is not better place. People happily ingest poison, pay their life’s work to hospitals which in turn inject more poison into people and make them more sick thus continuing the cycle.

Modern technique has made it possible to diminish enormously the amount of labor required to secure the necessaries of life for everyone. This was made obvious during the war.


The war showed conclusively that, by the scientific organization of production, it is possible to keep modern populations in fair comfort on a small part of the working capacity of the modern world. If, at the end of the war, the scientific organization, which had been created in order to liberate men for fighting and munition work, had been preserved, and the hours of the week had been cut down to four, all would have been well. Instead of that the old chaos was restored, those whose work was demanded were made to work long hours, and the rest were left to starve as unemployed. Why? Because work is a duty, and a man should not receive wages in proportion to what he has produced, but in proportion to his virtue as exemplified by his industry.


This is the morality of the Slave State, applied in circumstances totally unlike those in which it arose. No wonder the result has been disastrous.

If all you do is work, when will you have time to reflect upon what it is that you are doing? One thing I have noticed in my life is, if I am too close to something, I lose sight of the rational reasons and make a habit out of it without wondering if this is necessary. Taking a step back from the daily grind and looking at it, thinking about it, taking things and the rules that govern those things to their logical conclusion has always made me a better person.

Serious-minded persons, for example, are continually condemning the habit of going to the cinema, and telling us that it leads the young into crime. But all the work that goes to producing a cinema is respectable, because it is work, and because it brings a money profit. The notion that the desirable activities are those that bring a profit has made everything topsy-turvy. The butcher who provides you with meat and the baker who provides you with bread are praiseworthy, because they are making money; but when you enjoy the food they have provided, you are merely frivolous, unless you eat only to get strength for your work. Broadly speaking, it is held that getting money is good and spending money is bad.

Take some time off, read this and read it again and then read it again. There is nothing important that demands your attention from this.

  1. A great summary of Bertrand Russell over at Stanford