Array Sortieren (null Werte ans Ende)

  • Themenstarter Themenstarter TimoJAVA
  • Beginndatum Beginndatum
T

TimoJAVA

Gast
Hallo zusammen,
ich habe ein kleines Problem:

Ein Array soll sortiert werden, natürlich benutze ich dazu die Arrays.sort Methode mit meinem eigenen Comparator

Java:
Arrays.sort(archiveNPop, new Comparator<T>(){
					 @Override
			            public int compare(T entry1, T entry2) {
						 if(entry1 == null  && entry2 == null){
							return 0;
						 }else if(entry1 == null){
							return -1;
						 }else if(entry2 == null){
							return 1;
						 }else
						 	return entry1.compare(entry2);
			            }
			        });

Dabei sollen alle Werte die null sind möglichst ans Ende des Arrays gepackt werden. Leider bleiben sie genau da wo sie sind. Was mache ich falsch. Jemand eine Idee?

Grüße Timo
 
Abgesehen davon, dass sie nicht ans Ende sondern an den Anfang verschoben wurden, sollte das stimmen
Java:
import java.util.Arrays;
import java.util.Comparator;

public class SortTest
{
    public static void main(String[] args)
    {
        String array[] = {"B", null, "C", null, "A"};
        Arrays.sort(array, new Comparator<String>()
        {
            @Override
            public int compare(String entry1, String entry2)
            {
                if (entry1 == null && entry2 == null)
                {
                    return 0;
                }
                else if (entry1 == null)
                {
                    return 1;
                }
                else if (entry2 == null)
                {
                    return -1;
                }
                else
                    return entry1.compareTo(entry2);
            }
        });
        System.out.println(Arrays.toString(array));
    }
}
 

Zurück
Oben