Animal attacks on humans are not always random and are sometimes very justified. When the individual animal itself has been threatened or hurt by humans or when all or part of their social group is at risk it is no surprise when they retaliate.
The sperm whales that attacked the Essex and the Anne Alexander in the 1800s could logically be assumed to be retaliating as both had been injured by harpoons. Who wouldn’t fight back? It is equally possible that the attacking whales were protecting their pod.
It is common knowledge that working elephants in India most often attack their own mahout (handler) when they go on a ‘rampage’. Elephant training is notoriously brutal, so it makes sense that the person causing the pain would be the prime target when an elephant has finally had enough. In this case, the elephants are outside of their normal social structure so protection of other elephants is less likely.
One of my colleagues from India told me that he has seen entire herds of elephants walk through narrow village streets without causing any damage. Other times, villages are leveled. It would be interesting to compare villages that had aggressively chased elephants away with those that had to see if the attacks could be predicted.
Elephants and whales are intelligent species that live in social groups where they engage in complex interactions. In other words, there are rules. When humans break the rules of conduct, as understood by these animals, it is no surprise that the animals take revenge.