Using Generics to Swap and Sort Arrays of Different Types in Java

Bhavesh YadavBhavesh Yadav
2 min read

Sometimes, when coding in Java, you want to write reusable methods that work with different data types — like sorting arrays of integers or strings — without rewriting your code for each type.

In this post, I’ll share how I created a generic swap method and used it to sort arrays of either integers or strings with a custom order. Along the way, I’ll explain some common pitfalls and tips for comparing strings in Java.

The Problem

Imagine you want to sort arrays where elements can be "Low", "mid", "High" strings, or numbers like 1, 2, 3, and you want to order them consistently:

  • "Low" < "mid" < "High"

  • 1 < 2 < 3

How do you write a sorting method that works for both without duplicating code?

My Solution: Generic Swap and Custom Sort

First, I wrote a generic swap method:

public static <T> void swap(T[] arr, int i, int j) {
    T temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

This method works for any array of objects — String[], Integer[], or others.

Like for "Low", "mid", "High"

public void sortString(String[] arr) {
    int n = arr.length;
    int i = 0, j = 0, k = n - 1;

    while (i <= k) {
        if (arr[i].equals("mid")) {
            i++;
        } else if (arr[i].equals("Low")) {
            swap(arr, i, j);
            i++;
            j++;
        } else {  // "High"
            swap(arr, i, k);
            k--;
        }
    }
}

Then for Integers :

public void sortInteger(Integer[] arr) {
    int i = 0, j = 0, k = arr.length - 1;

    while (i <= k) {
        if (arr[i] == 2) {
            i++;
        } else if (arr[i] == 1) {
            swap(arr, i, j);
            i++;
            j++;
        } else {  // 3
            swap(arr, i, k);
            k--;
        }
    }
}
  • You’ve reused one generic utility (swap()).

  • Created two separate sorting logics depending on your data type and ordering rules.

  • clean code organization achieved

0
Subscribe to my newsletter

Read articles from Bhavesh Yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bhavesh Yadav
Bhavesh Yadav

SDE @ Arm