Category Archives: Tips and Tricks

Java toString(), equals() and hashCode() of a custom object

Let’s assume that we have a class Pair with two fields and we want to print a Pair instance object. Once we call the print method we will obtain something like Pair@10a5

class Pair<A, B> {
    A first;
    B last;
    
    public Pair(A first, B last) {
        this.first = first;
	this.last = last;
    }
    public A getFirst() {
        return first;
    }
    public void setFirst(A first) {
	this.first = first;
    }
    public B getLast() {
	return last;
    }
    public void setLast(B last) {
	this.last = last;
    }
}

That’s because in java every class derives from Object class and every time we print an instance of a class the default toString from Object class is called. The default implementation is composed of two main parts Type and HashCode. So for our Pair@10a5 we have the Type = Pair and the hashCode = 10a5.

public String toString() {
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

If we want to print something with a more clear representation we need to override the toString method in the Pair class.

@Override
public String toString() {
    return "Pair [first=" + first + ", last=" + last + "]";
}

In this way from the main of our class we can have ArrayList of Pair and print it. For each instance the overridden toString() method will be called instead of the one from the Object class.

public static void main(String[] args) {
   List<Pair<Long, Long>> pairsList = 
           Arrays.asList(new Pair(100L, 200L), new Pair(300L, 400L));
   System.out.println(pairsList);
}
-- > output 
[Pair [first=100, last=200], Pair [first=300, last=400]]

Another interesting thing we need to take in consideration are the equals and hashCode methods.

Let’s assume that we have a Set of Integer and we add the number “1” twice. The second add it’s not performed because the Set data structure detects that there is already a number “1” inserted.

We would expect that the same would happen if we had a Set of Pair object, right? But in the second case we are able to add both Pair even if they are equals.

Set<Integer> intSet = new HashSet<Integer>();
intSet.add(1);
intSet.add(1);
System.out.print(intSet);

--> output 
[1]

Set<Pair<Long, Long>> pairList = new HashSet<Pair<Long, Long>>();
pairList.add(new Pair(100L, 200L));
pairList.add(new Pair(100L, 200L));
System.out.print(pairList);

--> output
[Pair [first=100, last=200], Pair [first=100, last=200]]

This happens because in order to compare if two elements are equal the default equals and hashCode method from Object class are called. The Default implementation of these method will tell us:

  • equals(Object obj): if an object passed as argument is “equal to” the current instance and as default two objects are equal if and only if they are stored in the same memory address.
  • hashcode(): returns an integer representation of the object memory address. By default, this method will return a random integer that is unique for each instance and might change is we run multiple time the same application.

In order to make our Set understand how to deal with Pair object we need to override the equals and hashCode method in our Pair class. The complete implementation of our Pair class

class Pair<A, B> {
    A first;
    B last;

    public Pair(A first, B last) {
	this.first = first;
	this.last = last;
    }
    public A getFirst() {
	return first;
    }
   public void setFirst(A first) {
	this.first = first;
   }
   public B getLast() {
	return last;
   }
   public void setLast(B last) {
	this.last = last;
   }
   
   @Override
   public String toString() {
	return "Pair [first=" + first + ", last=" + last + "]";
   }
   
   @Override
   public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((first == null) ? 0 : first.hashCode());
	result = prime * result + ((last == null) ? 0 : last.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;
	Pair other = (Pair) obj;
	if (first == null) {
		if (other.first != null)
			return false;
	} else if (!first.equals(other.first))
		return false;
	if (last == null) {
		if (other.last != null)
			return false;
	} else if (!last.equals(other.last))
		return false;
	return true;
    }
}

Now if we ran again our main method we will only see one of the pair.

Set<Pair<Long, Long>> pairList = new HashSet<Pair<Long, Long>>();
pairList.add(new Pair(100L, 200L));
pairList.add(new Pair(100L, 200L));
System.out.print(pairList);

--> output
[Pair [first=100, last=200]]

Spring @RestController vs @Controller

To understand the difference between @RestController and @Controller we can think about the main difference between a REST API and a Web application. The response of a REST API is generally JSON or XML; in a web application, instead, the response is usually a view (some html + css) intended for human viewers.

This is also the main difference between @Controller and @RestController annotation. Basically in a spring mvc @Controller the handler method returns the response “view name” which is resolved to a view technology file (e.g. JSP) and the parsed view content is sent back to browser client. It just create a map of the model object and find a view. If we want instead to bundle the return value yo a web response body we can use the @ResponseBody annotation and no view resolver is needed.

For example assuming that we have a view and a greeting Api in a MVCController that take a param as input and return a view we can use @Controller annotation

// Path of view template
/src/main/resources/templates/greeting.html

@Controller
public class MVCController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required = 
              false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        // We can return a view name that is present in 
        return "greeting";
    }
}

The @RestController simply returns the object and object data is directly written into HTTP response as JSON or XML. One notice is that in Spring MVC the @RestController annotation is a combination of @Controller and @ResponseBody annotation.

@Controller
@ResponseBody
public class MVCController {
  // your logic
}

@RestController
public class RestFulController { 
  // your logic
}

List to int[] in Java

How to convert a List<Integer> to a int[] in Java 8? Using Java 8 collections stream() function and then mapping to ints, we get an IntStream. With the IntStream we can call toArray() which gives us the int[]

public int[] toIntArray(List<Integer> list){
   return list.stream().mapToInt(Integer::intValue).toArray();
}

From bash to zsh…git and prompt configuration

After a really long journey I decided to retire my long-lasting and trustworthy companion, my 2012 MacBook Air. I spent quite some time to decide which new model to buy; in the end the presence of the touch bar made me avoid all other models and going for the latest 2020 MacBook Air.

I didn’t want to use one of my time capsule backup but have a new clean env to setup and so first thing first: git, bash-completion and customization of the prompt on zsh shell on macOs Catalina. I used brew to do it.

brew install git bash-completion

And then to make the completion available in zsh as suggested by homebrew website you must get the Homebrew-managed zsh site-functions on your FPATH before initialising zsh’s completion facility, so I added the following in the ~/.zshrc file:

if type brew &>/dev/null; then
  FPATH=$(brew --prefix)/share/zsh/site-functions:$FPATH
  autoload -Uz compinit && compinit
fi

Compinit was complaining about insecure directories, so I listed the insecure directory and added the correct permission for those.

zsh compinit: insecure directories, run compaudit for list.
Ignore insecure directories and continue [y] or abort compinit [n]? 

compaudit

This is because those folders are group writable, so I changes it:

compaudit | xargs chmod g-w

I do like do see in my prompt both the user and the machine name, the path I’m on and if it’s a git repository the branch name and adding some color. Next step will be adding some more icon to show the status of the git repository.

# Load version control information
autoload -Uz vcs_info
precmd() { vcs_info }

# Format the vcs_info_msg_0_ variable
zstyle ':vcs_info:git:*' formats '(%b)'

autoload -U colors && colors

# Set up the prompt (with git branch name)
setopt PROMPT_SUBST
PROMPT='%n@%m %F{green}${PWD/#$HOME/~}%f %F{yellow}${vcs_info_msg_0_}%f > '
zsh custom prompt
work in progress of my zsh prompt customization

Ruby and its destructive methods…

In ruby there are methods followed by a “!” symbol (exclamation mark). These methods alter the object itself.

For example in the Array class there are two versions of shuffle method
shuffle and shuffle!.

a = [1,2,3, 4] => [1, 2, 3, 4]
a.object_id => 70279519801380
a.shuffle.object_id => 70279519867040
a.shuffle!.object_id => 70279519801380

  • Shuffle version returns a new array with elements of self shuffled and as a.shuffle.object_id shows a different value from a.object_id.
  • shuffle! modifies the object itself,  shuffling elements in self in place and a.shuffle!.object_id shows the same object_id of a.object_id.