سؤال

Introduction

I'm trying to make a custom sorting method for a String Array, but my code isn't working for some reason. The method I'm writing will take inputs like this

{"/",
 "/games/",
 "/homework/",
 "/usr/",
 "/games/snake/",
 "/temp/downloads/",
 "/usr/local/",
 "/usr/local/bin/"}

I want to sort as follows:

  1. By number of directories, i.e. the "/" would come first then "/games/", etc...
  2. If it's a tie it should be sorted alphabetically according to the last directory.

My Code

import java.util.*;

public class Dirsort {
    public String[] sort(String[] dirs) {
        ArrayList<Sort> mySort = new ArrayList<Sort>();

        for (String d: dirs){
            String l = d.split("/")[-1];
            int di = d.length();
            mySort.add(new Sort(di,l,d));
        }
        Collections.sort(mySort);
        String [] ans = new String [mySort.size()];
        int count = 0;
        for (Sort s: mySort){
            ans[count] = s.toString();
            count++;
        }
        return ans;
    }
    class Sort implements Comparable<Sort>{
        private int d;
        private String last;
        private String dir;

        public Sort(int myD, String myLast, String myDir){
            d = myD;
            last = myLast;
            dir = myDir;
        }

        public String toString(){
            return dir;
        }

        @Override
        public int compareTo(Sort arg0) {
            // TODO Auto-generated method stub
            if (this.d == arg0.d){
                return this.last.compareTo(arg0.last);
            }
            return this.d-arg0.d;
        }   
    }
}

The Problem

I get the following error when I test my code and I can't figure out why.

runtime exception:java.lang.ArrayIndexOutOfBoundsException: -1java.lang.ArrayIndexOutOfBoundsException: -1 at Dirsort.sort(Dirsort.java:6) at Tester$1.run(Tester.java:48) ["/", "/usr/", "/usr/local/", "/usr/local/bin/", "/games/", "/games/snake/", "/homework/", "/temp/downloads/" ]

هل كانت مفيدة؟

المحلول

You can't index an array with -1 in Java. In Python, you might have gotten the last element of the list. Welcome to Java, where you need to store the array before you can use its length as an index to itself.

String[] dSplit = d.split("/");
String l = dSplit [dSplit.length-1];

نصائح أخرى

The simplest and more readable implementation of your problem is using a Comparator instead of Comparable. Comparable is better suited for your own classes.

import java.util.*;

public class Sort {
    public static void main(String[] args) {
        String[] testArray = {
            "/",
            "/games/",
            "/homework/",
            "/usr/",
            "/games/snake/",
            "/temp/downloads/",
            "/usr/local/",
            "/usr/local/bin/"
        };

        Comparator<String> pathComparator = new PathComparator();
        Arrays.sort(testArray, pathComparator);

        System.out.println(Arrays.toString(testArray));
    }

    static class PathComparator implements Comparator<String> {

        public int compare(String path1, String path2) {
            String[] dirs1 = path1.split("/");
            String[] dirs2 = path2.split("/");

            if (dirs1.length < dirs2.length) {
                return -1;
            }
            else if (dirs1.length > dirs2.length) {
                return 1;
            }
            else {
                String lastDir1 = dirs1[dirs1.length - 1];
                String lastDir2 = dirs2[dirs2.length - 1];

                return lastDir1.compareTo(lastDir2);
            }
        }
    }
}

Also note that using descriptive names for variables make the code much more readable. When your code contains variables named d, l, arg0 etc., it becomes unreadable. For example, l can mean length or last or list. In 2 weeks you won't remember what it meant.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top