简体   繁体   中英

Selection sorting java array

I'm doing a project in which I must generate an array list the size of a user input(in this case i chose 4), with random numbers between -1000 and 1000. Then I have to have it do a selection sort and display both the unsorted numbers in output1 and the sorted numbers in output2 Heres what I have thus far

ArrayList <Integer> unSortedNumbers = new ArrayList <Integer>();
Integer [] numberSort;

...

private void SortActionPerformed(java.awt.event.ActionEvent evt) {
    String input, sortedNumberOutput = "";
    int int1, int2 = 0, min = -1000, max = 1000, j, minimum, temp = 0;
    input = Input.getText();
    int1 = Integer.parseInt(input);

    Random number = new Random();

    while (int2 < int1) {
        for (int i = 0; i < int1; i++) {
            int randomInt = number.nextInt(max - min + 1) + min;
            unSortedNumbers.add(randomInt);
            int1--;
        }
    }

    numberSort = new Integer[unSortedNumbers.size()];
    unSortedNumbers.toArray(numberSort);


    for (int i = 0; i < numberSort.length; i++) {
        sortedNumberOutput += numberSort[i] + (i != numberSort.length ? "," : "");

    }
    if (Selection.isSelected() && Ascending.isSelected()) {
        for (int i = 0; i < numberSort.length - 1; i++) {
            minimum = numberSort[i];
            for (j = i + 1; j <= numberSort.length - 1; j++) {
                if (minimum > numberSort[j]) {
                    numberSort[temp] = numberSort[i];
                    numberSort[i] = numberSort[j];
                    numberSort[j] = numberSort[temp];
                }
            }
        }
    }

    Output1.setText("Unsorted Numbers " + unSortedNumbers);
    Output2.setText("Sorted Numbers " + numberSort);
    unSortedNumbers.clear();
    numberSort = null;
}                               

So when I run that, the unSortedNumbers are displayed properly in output1, but instead of displaying the sorted numbers in output2, it displays this : Sorted Numbers [Ljava.lang.Integer;@7a279c

I'm not sure why this is happening, my could is probably wrong somewhere, If you can help, thank you!

What you are seeing is the result of the default toString() method being called on an array object. [Ljava.lang.Integer tells you it is an array of Integers and the @7a279c gives you the hex string of the hashcode. Do as ZouZou suggests and use Arrays.toString(unSortedNumbers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM