Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
Why is my arraylist not getting sorted using comparator interface?

So i tried sorting an arraylist which consists of only integer elements in descending order using comparator interface but after printing the array list it shows the elements in the order in which input was given.

here's my code...

import java.io.*;
import java.util.*;
public class Test {
    public static class Sort implements Comparator<Integer>{
        public int compare(Integer a,Integer b){
            if(a<b){
                return 1;
            }
            return 0;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
        ArrayList<Integer> arraylist=new ArrayList<>();
        for(int i=0;i<n;i++){
            arraylist.add(Integer.parseInt(br.readLine()));
        }
        Collections.sort(arraylist,new Sort());
        System.out.println(arraylist);
        br.close();
    }
}

So what i learnt is that if the compare method returns a positive value then swapping of the objects take place. So i returned 1 if a<b for sorting the array in descending order. Where did i go wrong?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

As the Comments discuss, your code violates the terms of the Comparator contract. Per Jon Skeet, the Javadoc explains that "The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y."

And, you are working too hard.

When you want to reverse the order, descending rather than ascending, simply call Comparator#reversed. This call returns a new Comparator object for you to use.

Since Integer class implements Comparable, you need not define an initial comparator. Simply call Comparator#reverseOrder. This call reverses the natural order of the objects.

List< Integer > myList = new ArrayList <> ( List.of( 7 , 1 , 42 ) ) ;
myList.sort( Comparator.reverseOrder() );

See this code run live at IdeOne.com.

[7, 1, 42]

[42, 7, 1]

over 4 years ago · Santiago Trujillo Relatório

0

Your code fails because you did not return value "-1" and return "0" is not in else statement. So when you performing sort() function it return always "0" for every comparison.

Simply just rewrite an if statement and it works fine.

See example below:

public static class Sort implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
        if (a < b) {
            return 1;
        } else if (a == b) {
            return 0;
        } else return -1;
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda