How to implement the hashCode and equals method using Apache Commons?

This code snippet show you how to use HashCodeBuilder and EqualsBuilder class from the Apache Commons Lang library to implement the hashCode() and equals() method of an object. To use both of these classes we just need to create instance of these classes and append the properties that we will use to calculate the hashcode and to test for equality.

Implementing the hashCode() method first by creating the hashCode() method. Add the @Override annotation to make sure that we’ve overridden the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re going to use to calculate the hashcode. The final result of the actual hashcode can be obtained by calling the toHashCode() from the instance of HashCodeBuilder.

/**
 * Implement the hashCode method using HashCodeBuilder.
 */
@Override
public int hashCode() {
    return new HashCodeBuilder().append(id).append(name).toHashCode();
}

We do the same to create the equals() method. First create the method, it takes a single argument type of java.lang.Object. Add the @Override annotation to make sure we override the correct method. On the first line you can check to see if the passed object is an instance of the same object, we use the instanceof operator. We then compare the values stored in both object using the EqualsBuilder class. To get the equality result you must remember to call the isEquals() method.

/**
 * Implement the equals method using the EqualsBuilder.
 */
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof DummyUser that)) {
        return false;
    }
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class DummyUser {
    private Long id;
    private String name;

    /**
     * Constructor to create an instance of this class.
     */
    public DummyUser() {
    }

    public static void main(String[] args) {
        DummyUser user1 = new DummyUser();
        user1.setId(10L);
        user1.setName("Carol");

        DummyUser user2 = new DummyUser();
        user2.setId(10L);
        user2.setName("Carol");

        System.out.println("user1.hashCode() = " + user1.hashCode());
        System.out.println("user2.hashCode() = " + user2.hashCode());

        System.out.println("user1.equals(user2) = " + user1.equals(user2));
    }

    // Getters & Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Implement the hashCode method using HashCodeBuilder.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(id).append(name).toHashCode();
    }

    /**
     * Implement the equals method using the EqualsBuilder.
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DummyUser that)) {
            return false;
        }
        return new EqualsBuilder().append(this.id, that.id)
                .append(this.name, that.name).isEquals();
    }
}

The result of our code are:

user1.hashCode() = 64902380
user2.hashCode() = 64902380
user1.equals(user2) = true

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Maven Central

How do I checks if two dates are on the same day?

In this example you’ll learn how to find out if two defined date objects are on the same day. It means that we are only interested in the date information and ignoring the time information of these date objects. We’ll be using an API provided by the Apache Commons Lang in this example. So here is the code snippet:

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class CheckSameDay {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date();

        // Checks to see if the dates is on the same day.
        if (DateUtils.isSameDay(date1, date2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", date1, date2);
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Checks to see if the calendars is on the same day.
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", cal1, cal2);
        }

        cal2.add(Calendar.DAY_OF_MONTH, 10);
        if (!DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is not on the same day.", cal1, cal2);
        }
    }
}

The example result produced by this snippet are:

31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 10/11/2021 is not on the same day.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Maven Central

How do I create File object from URL?

The code snippet below use the FileUtils.toFile(URL) method that can be found in the commons-io library to convert a URL into a File. The url protocol should be file or else null will be returned.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class URLToFileObject {
    public static void main(String[] args) throws Exception {
        // FileUtils.toFile(URL url) convert from URL the File.
        String data = FileUtils.readFileToString(Objects.requireNonNull(
                        FileUtils.toFile(URLToFileObject.class.getResource("/data.txt"))),
                StandardCharsets.UTF_8);
        System.out.println("data = " + data);

        // Creates a URL with file protocol and convert it into File object.
        File file = FileUtils.toFile(new URL("file:///D:/demo.txt"));
        data = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        System.out.println("data = " + data);
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.0</version>
</dependency>

Maven Central

How do I create a BasicDataSource object?

This example demonstrates how to use the BasicDataSource class of Apache Commons DBCP to create a basic requirements for database connection. The configuration of the data source can be defined using some property method provided by this class. The basic properties are the driver classname, connection url, username and password.

After the datasource ready we can obtain a connection by calling the getConnection() method of the datasource. This method might throw an SQLException when errors occurs.

package org.kodejava.commons.dbcp;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BasicDataSourceExample {
    public static void main(String[] args) {
        // Creates a BasicDataSource and defines its properties
        // including the driver class name, JDBC url, username
        // and password.
        try (BasicDataSource dataSource = new BasicDataSource()) {
            dataSource.setUrl("jdbc:mysql://localhost/kodejava");
            dataSource.setUsername("kodejava");
            dataSource.setPassword("s3cr*t");

            // Get a connection from the data source and do a
            // database query with the obtained connection.
            try (Connection conn = dataSource.getConnection();
                 PreparedStatement stmt = conn.prepareStatement("SELECT * FROM author")) {
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    System.out.println("Author name: " + rs.getString("author_name"));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

We can simplify the code above so that we don’t have to close the PreparedStatement and Connection manually like we did in the finally block in the code snippet. We can use try-with-resources to automatically close resources. An example can be seen in the following example: How to automatically close resources in JDBC?.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a database connection pool?

This example show you how to create a connection pool implementation using the Apache Commons DBCP library.

package org.kodejava.commons.dbcp;

import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ConnectionPoolExample {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    private GenericObjectPool<PoolableConnection> connectionPool = null;

    public static void main(String[] args) throws Exception {
        ConnectionPoolExample demo = new ConnectionPoolExample();
        DataSource dataSource = demo.setUp();
        demo.printStatus();

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM author")) {
            demo.printStatus();

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println("Author name: " + rs.getString("author_name"));
            }
        }

        demo.printStatus();
    }

    public DataSource setUp() {
        // Creates a connection factory object which will be used by
        // the pool to create the connection object. We pass the
        // JDBC url info, username and password.
        ConnectionFactory cf = new DriverManagerConnectionFactory(
                ConnectionPoolExample.URL,
                ConnectionPoolExample.USERNAME,
                ConnectionPoolExample.PASSWORD);

        // Creates a PoolableConnectionFactory that will wrap the
        // connection object created by the ConnectionFactory to add
        // object pooling functionality.
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
        pcf.setValidationQuery("SELECT 1");

        // Creates an instance of GenericObjectPool that holds our
        // pool of connections object.
        GenericObjectPoolConfig<PoolableConnection> config = new GenericObjectPoolConfig<>();
        config.setTestOnBorrow(true);
        config.setMaxTotal(10);
        connectionPool = new GenericObjectPool<>(pcf, config);
        pcf.setPool(connectionPool);

        return new PoolingDataSource<>(connectionPool);
    }

    private GenericObjectPool<PoolableConnection> getConnectionPool() {
        return connectionPool;
    }

    /**
     * Prints connection pool status.
     */
    private void printStatus() {
        System.out.println("Max   : " + getConnectionPool().getNumActive() + "; " +
                "Active: " + getConnectionPool().getNumActive() + "; " +
                "Idle  : " + getConnectionPool().getNumIdle());
    }
}

The code show the following status as output example:

Max   : 0; Active: 0; Idle  : 0
Max   : 1; Active: 1; Idle  : 0
Author name: Raoul-Gabriel Urma
Author name: Mario Fusco
Author name: Alan Mycroft
Max   : 0; Active: 0; Idle  : 1

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I capitalize each word in a string?

This example show you how to capitalize a string. We use methods from WordUtils class provided by the Apache commons-text;. We can use the WordUtils.capitalize(str) or WordUtils.capitalizeFully(str).

Let’s see an example below:

package org.kodejava.commons.text;

import org.apache.commons.text.WordUtils;

public class WordCapitalize {
    public static void main(String[] args) {
        // Capitalizes all the whitespace separated words in a string,
        // only the first letter of each word is capitalized.
        String str = WordUtils.capitalize(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);

        // Capitalizes all the whitespace separated words in a string
        // and the rest string to lowercase.
        str = WordUtils.capitalizeFully(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);
    }
}

And here are the result of the program:

str = The Quick Brown Fox JUMPS OVER The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>

Maven Central

How do I move directory to another directory with its entire contents?

Below is an example to move one directory with all its child directory and files to another directory. We can use the FileUtils.moveDirectory() method call to simplify the process.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class DirectoryMove {
    public static void main(String[] args) {
        String source = "F:/Temp/source";
        File srcDir = new File(source);

        String destination = "F:/Temp/target";
        File destDir = new File(destination);

        try {
            // Move the source directory to the destination directory.
            // The destination directory must not exist prior to the
            // move process.
            FileUtils.moveDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.0</version>
</dependency>

Maven Central

How do I copy directory with all its contents to another directory?

To copy a directory with the entire child directories and files we can use a handy method provided by the Apache Commons IO FileUtils.copyDirectory(). This method accept two parameters, the source directory and the destination directory. The source directory should be available while if the destination directory doesn’t exist it will be created.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class DirectoryCopy {
    public static void main(String[] args) {
        // An existing directory to copy.
        String source = "F:/Temp/source";
        File srcDir = new File(source);

        // The destination directory to copy to. This directory
        // doesn't exist and will be created during the copy
        // directory process.
        String destination = "F:/Temp/target";
        File destDir = new File(destination);

        try {
            // Copy source directory into destination directory
            // including its child directories and files. The
            // destination directory will be created if it does
            // not exist. This copy process also preserve the
            // date information of the file.
            FileUtils.copyDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.0</version>
</dependency>

Maven Central

How do I copy a URL into a file?

The code snippet below show you how to use the FileUtils.copyURLToFile(URL, File) method of the Apache Commons IO library to help you to copy the contents of a URL directly into a file.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class URLToFile {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.google.com");
            File destination = new File("google.html");

            // Copy bytes from the URL to the destination file.
            FileUtils.copyURLToFile(url, destination);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.0</version>
</dependency>

Maven Central

How do I get free space of a drive or volume?

The getFreeSpaceKb(String path) method in the FileSystemUtils class can help you to calculate the free space of a drive or volume in kilobytes.

Beside using commons-io solution, you can use the File.getFreeSpace() method call provided in the Java 1.6 API. You can find an example of it in the following link: How do I get total space and free space of my disk?.

package org.kodejava.commons.io;

import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;

import java.io.IOException;

public class DiskFreeSpace {
    public static void main(String[] args) {
        try {
            String path = "F:/Temp";
            long freeSpaceKB = FileSystemUtils.freeSpaceKb(path);
            long freeSpaceMB = freeSpaceKB / FileUtils.ONE_KB;
            long freeSpaceGB = freeSpaceKB / FileUtils.ONE_MB;

            System.out.println("Size of " + path + " = " + freeSpaceKB + " KB");
            System.out.println("Size of " + path + " = " + freeSpaceMB + " MB");
            System.out.println("Size of " + path + " = " + freeSpaceGB + " GB");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

An example result of the code above is:

Size of F:/Temp = 323413052 KB
Size of F:/Temp = 315833 MB
Size of F:/Temp = 308 GB

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.0</version>
</dependency>

Maven Central