What is Java Sort?

Asked

Viewed 594 times

4

Every programmer know that a list of arrays are printed in an orderly way, but in the middle of the way sort().

The result of the impression was this:

Abacaxi
Banana
Laranja
Manga

I thought it would print that way:

 Banana 
 Laranja 
 Manga 
 Abacaxi

I don’t know how the sort() behaves, but from what I’m seeing he prints 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);
        }
    }
}
  • Explain why you think this should be the result, it doesn’t make any sense what you are asking. You want to know what the function sort() does? Is that it? If it is, I could not ask more simply?

  • @Maniero I just wanted to know why he printed so Pineapple Banana Orange Mango instead of so Banana Orange Mango Pineapple . in fact I don’t know how Sort behaves.

2 answers

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/classified(Sorted) in this case at least in alphabetical order.

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

6


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

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

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

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

Job documentation sort().

See more in What is the difference between ordered, unordered and Sorted?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.