You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Album对象数组变量覆盖问题与四种降序排序算法实现需求

Hey there! Let's break down your two problems with clear explanations and actionable code examples that you can implement immediately.


Problem 1: Fixing the "Last Album Object Overwriting Others" Issue

This is a super common gotcha in OOP, so let's walk through the most likely causes and how to fix them.

Common Root Causes

  • Misusing Static Variables: If your Album class declares properties as static, every instance shares the same value for those properties. The last time you set the value, it overwrites everything before it.
  • Reusing the Same Object Instance: If you assign the same Album object to multiple positions in your array instead of creating new instances, modifying one (including the last one) changes all references.
  • Shallow Copy Issues: If Album has reference-type properties (like a List<String> for tracks), copying the object without deep copying those references means multiple instances point to the same underlying data.

Fix Examples

❌ Bad: Static Variables in Album

public class Album {
    // Static = shared across ALL Album instances
    public static String title;
    public static int releaseYear;

    public Album(String title, int releaseYear) {
        Album.title = title;
        Album.releaseYear = releaseYear;
    }
}

✅ Good: Instance Variables in Album

public class Album {
    // Instance variables = each Album has its own copy
    private String title;
    private int releaseYear;

    public Album(String title, int releaseYear) {
        this.title = title;
        this.releaseYear = releaseYear;
    }

    // Getters are needed for sorting later
    public String getTitle() { return title; }
    public int getReleaseYear() { return releaseYear; }

    @Override
    public String toString() {
        return String.format("Album{title='%s', year=%d}", title, releaseYear);
    }
}

✅ Correct Way to Create the Album Array

public class Main {
    public static void main(String[] args) {
        Album[] albumCollection = new Album[3];
        // Create a NEW Album instance for each array slot
        albumCollection[0] = new Album("Midnights", 2022);
        albumCollection[1] = new Album("1989", 2014);
        albumCollection[2] = new Album("Reputation", 2017);

        // Now each Album has independent values—no overwriting!
        for (Album album : albumCollection) {
            System.out.println(album);
        }
    }
}

Problem 2: Implementing Four Sorting Algorithms (Descending Order + Album Support)

We'll use Java for these implementations, leveraging the Comparator interface to make them generic—so they work for both integer arrays (descending) and Album objects (sorted by title, release year, etc.).

1. Insertion Sort (In-Place)

Insertion sort builds a sorted array one element at a time by inserting each unsorted element into its correct position.

/**
 * In-place insertion sort with custom sorting logic
 * @param arr Array to sort
 * @param comparator Defines sort order (e.g., descending for integers)
 * @param <T> Type of elements in the array
 */
public static <T> void insertionSort(T[] arr, Comparator<T> comparator) {
    // Start from the second element (first is trivially sorted)
    for (int i = 1; i < arr.length; i++) {
        // Store the current element to insert
        T key = arr[i];
        // Pointer to the end of the sorted portion
        int j = i - 1;

        // Shift elements in the sorted portion right if they're smaller than the key (for descending order)
        while (j >= 0 && comparator.compare(key, arr[j]) > 0) {
            arr[j + 1] = arr[j];
            j--;
        }
        // Insert the key into its correct position
        arr[j + 1] = key;
    }
}

2. Bubble Sort

Bubble sort repeatedly swaps adjacent elements if they're in the wrong order, "bubbling" the largest unsorted element to its correct position each pass.

/**
 * Bubble sort with custom sorting logic
 * @param arr Array to sort
 * @param comparator Defines sort order
 * @param <T> Type of elements in the array
 */
public static <T> void bubbleSort(T[] arr, Comparator<T> comparator) {
    int n = arr.length;
    // Outer loop: tracks how many elements are already sorted at the end
    for (int i = 0; i < n - 1; i++) {
        // Flag to check if any swaps happened (early exit if array is sorted)
        boolean swapped = false;
        // Inner loop: iterate through unsorted portion
        for (int j = 0; j < n - i - 1; j++) {
            // Swap if current element is smaller than next (for descending order)
            if (comparator.compare(arr[j], arr[j + 1]) < 0) {
                T temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
            }
        }
        // No swaps = array is sorted, break early
        if (!swapped) break;
    }
}

3. Selection Sort

Selection sort finds the largest element in the unsorted portion and swaps it with the first element of the unsorted portion.

/**
 * Selection sort with custom sorting logic
 * @param arr Array to sort
 * @param comparator Defines sort order
 * @param <T> Type of elements in the array
 */
public static <T> void selectionSort(T[] arr, Comparator<T> comparator) {
    int n = arr.length;
    // Outer loop: marks the start of the unsorted portion
    for (int i = 0; i < n - 1; i++) {
        // Assume the first element of unsorted portion is the largest
        int maxIndex = i;
        // Inner loop: find the actual largest element in unsorted portion
        for (int j = i + 1; j < n; j++) {
            if (comparator.compare(arr[j], arr[maxIndex]) > 0) {
                maxIndex = j;
            }
        }
        // Swap the largest element with the first element of unsorted portion
        T temp = arr[maxIndex];
        arr[maxIndex] = arr[i];
        arr[i] = temp;
    }
}

4. Quick Sort

Quick sort uses divide-and-conquer: pick a pivot, partition the array into elements larger/smaller than the pivot, then recursively sort the subarrays.

/**
 * Quick sort with custom sorting logic
 * @param arr Array to sort
 * @param comparator Defines sort order
 * @param <T> Type of elements in the array
 */
public static <T> void quickSort(T[] arr, Comparator<T> comparator) {
    quickSortHelper(arr, 0, arr.length - 1, comparator);
}

/**
 * Recursive helper for quick sort
 * @param arr Array to sort
 * @param low Left boundary of current subarray
 * @param high Right boundary of current subarray
 * @param comparator Defines sort order
 * @param <T> Type of elements in the array
 */
private static <T> void quickSortHelper(T[] arr, int low, int high, Comparator<T> comparator) {
    if (low < high) {
        // Partition the array and get the pivot's final position
        int pivotIndex = partition(arr, low, high, comparator);
        // Recursively sort left subarray (elements > pivot)
        quickSortHelper(arr, low, pivotIndex - 1, comparator);
        // Recursively sort right subarray (elements < pivot)
        quickSortHelper(arr, pivotIndex + 1, high, comparator);
    }
}

/**
 * Partition the array around a pivot (last element)
 * @param arr Array to partition
 * @param low Left boundary
 * @param high Right boundary (pivot element)
 * @param comparator Defines sort order
 * @param <T> Type of elements in the array
 * @return Final index of the pivot element
 */
private static <T> int partition(T[] arr, int low, int high, Comparator<T> comparator) {
    // Choose the last element as pivot
    T pivot = arr[high];
    // Index of the last element larger than the pivot
    int i = low - 1;

    // Iterate through elements from low to high-1
    for (int j = low; j < high; j++) {
        // If current element is >= pivot (for descending order), move it to the larger section
        if (comparator.compare(arr[j], pivot) >= 0) {
            i++;
            // Swap current element with the next position in the larger section
            T temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    // Place the pivot in its correct position (between larger and smaller elements)
    T temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;

    return i + 1;
}

Test Examples

Integer Array (Descending Order)

import java.util.Arrays;
import java.util.Comparator;

public class SortTests {
    public static void main(String[] args) {
        Integer[] numbers = {3, 5, 1, 7, 2};
        // Comparator for descending integer order
        Comparator<Integer> intDesc = (a, b) -> b - a;

        System.out.println("Original: " + Arrays.toString(numbers));
        insertionSort(numbers, intDesc);
        System.out.println("Insertion Sort (Desc): " + Arrays.toString(numbers));

        // Reset array for next sort
        numbers = new Integer[]{3, 5, 1, 7, 2};
        bubbleSort(numbers, intDesc);
        System.out.println("Bubble Sort (Desc): " + Arrays.toString(numbers));

        numbers = new Integer[]{3, 5, 1, 7, 2};
        selectionSort(numbers, intDesc);
        System.out.println("Selection Sort (Desc): " + Arrays.toString(numbers));

        numbers = new Integer[]{3, 5, 1, 7, 2};
        quickSort(numbers, intDesc);
        System.out.println("Quick Sort (Desc): " + Arrays.toString(numbers));
    }
}

Album Object Sort (By Release Year, Descending)

import java.util.Comparator;

public class AlbumSortTests {
    public static void main(String[] args) {
        Album[] albums = {
            new Album("Midnights", 2022),
            new Album("1989", 2014),
            new Album("Reputation", 2017),
            new Album("Folklore", 2020)
        };

        // Comparator for Album descending by release year
        Comparator<Album> albumYearDesc = (a1, a2) -> a2.getReleaseYear() - a1.getReleaseYear();

        System.out.println("Original Albums:");
        for (Album album : albums) System.out.println(album);

        insertionSort(albums, albumYearDesc);
        System.out.println("\nInsertion Sort (By Year Desc):");
        for (Album album : albums) System.out.println(album);

        // Test other sorts the same way—just pass the comparator!
    }
}

内容的提问来源于stack exchange,提问作者Vinh Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:58:12