What is Java's sort?

4

Every programmer knows that a list of arrays is printed neatly, but in the middle of the path has sort() .

The result of this impression was:

Abacaxi
Banana
Laranja
Manga

I imagined it would print this way:

 Banana 
 Laranja 
 Manga 
 Abacaxi

I do not know how sort() behaves, but from what I can see it prints by following the alphabetical order when it comes to strings ?

public class Test {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Banana", "Laranja", "Manga", "Abacaxi");

        Collections.sort(fruits);
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
    
asked by anonymous 14.10.2018 / 13:54

2 answers

6

The sort() function sorts lists of data. In its simplest form it uses an increasing order. If the data is text it is clear that the order is alphabetical.

Every list has some order, it can be a natural order or it can be an adapted order. The sort() function changes the order by sorting each element alphabetically.

It is obvious that if you apply a function to a list it is likely that this list will be modified in some way. It would not make sense to use the function and expect everything to be the same.

Then after calling this function, which can be very time consuming if the list is too large, the list will have a new "definitive" order. Of course the list will not always keep everything alphabetically if you manipulate the data, the list structure is not naturally sorted, so future manipulations will not be sorted, if you need the sort you will have to run sort() again. If you always have to do this, it is better to use another type of structure that is automatically classified, which is not the case with ArrayList .

Function documentation sort() .

See more in What's the difference between ordered, unordered and sorted? .

    
14.10.2018 / 14:20
6

I think you're confusing the terms "ordered" and "sorted" .

The Array represents a set of elements with a certain order ( ordered ) but not necessarily ordered / sorted ( sorted ) at least in this case alphabetically.

It is "ordered" because the items maintain an order / sequence that comes from their position (index) in the array.

    
14.10.2018 / 14:19