Home > Java > javaTutorial > body text

How to use generics to implement array sorting in Java

WBOY
Release: 2023-05-16 16:22:06
forward
1035 people have browsed it

1. Sequential shrinkage of integer arrays

public static int seqSearch(int[] arr, int first, int last, int target) {        for (int i = first; i < last; i++)            if (arr[i] == target)                return i;            return -1;    }
Copy after login

1.1 Abstract the above method, ***Let us think of using java’s Object reference to implement the universal method

public static int seqSearch(Object[] arr, int first, int last, Object target) {        for (int i = first; i < last; i++)            if (arr[i].equals(target))                return i;            return -1;    }
Copy after login

2.1 It seems that the reference of Object is very convenient, and the second sequential search can use float, double, String, etc. Problems will arise if we want to study further

public static void selectionSort(int[] arr) {        int n = arr.length, smallIndex = 0;        for (int i = 0; i < n; i++) { // 遍历array数组            smallIndex = i;            for (int j = i + 1; j < n; j++)                if (arr[smallIndex] > arr[j]) // 选择最小的索引j                    smallIndex = j;            // if (smallIndex != i) {            exchange(arr, i, smallIndex);// 交换array[i]与 min(array[i+1,..,n])            // }        }    }
Copy after login

2.2 The above code is a sequential sorting algorithm. If we want to write a general method, we must force the object type to be one that implements the Comparable interface. method.

JVM will throw a warning when processing type forced conversion: uncheck cast

@SuppressWarnings("unchecked")    public static void selectionSort(Object[] arr) {            int n = arr.length, smallIndex = 0;        for (int i = 0; i < n; i++) { // 遍历array数组            smallIndex = i;            for (int j = i + 1; j < n; j++)                if (((Comparable<Object>)arr[smallIndex]).compareTo(((Comparable<Object>)arr[j])) > 0) // 选择最小的索引j                    smallIndex = j;            // if (smallIndex != i) {            exchange(arr, i, smallIndex);// 交换array[i]与 min(array[i+1,..,n])            // }        }    }
Copy after login

It can be seen from this that Object reference is used to deal with common problems. When using actual parameters, if If the Comparable interface is not implemented, the compiler will throw a castClassException runtime exception. Such a program is unsafe.

3.1 Use Object reference to generalize an algorithm (such as sequential search). By using the Object reference and target value of the array, as long as the data type implements the equals method, the data class to be compared in the algorithm must implement the Comparable interface. Now we use java generics to solve this problem

public static <T extends Comparable<? super T>> void selectionSort(T[] arr){        int n = arr.length;        int smallIndex;        for (int i = 0; i < n-1; i++) {            smallIndex=i;            for (int j = i+1; j < n; j++)                 if (arr[j].compareTo(arr[smallIndex])<0)                     smallIndex=j;            exchange(arr, smallIndex, i);        }    }
Copy after login

The static method selectionSort() in the Arrays class, this method deals with integer types. To use the generic version to implement this algorithm, since the two elements in the generic type array T[] need to be compared, the object type or its superclass that passes the actual parameter must implement the Comparable interface.

The above is the detailed content of How to use generics to implement array sorting in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template