当数组未满时,排序数组不起作用

时间:2016-12-04 14:48:47

标签: java arrays sorting

我创建了一些插入,选择和泡泡排序。它们似乎在对象数组已满时工作但是当我使数组有5并且只用3填充它时,它在我排序时出错。这是我的排序代码。

public class CityList {
    private City[] city;
    private Integer numberOfCities;

    public CityList (Integer cityListSize){
        this.city=new City[cityListSize];
        this.numberOfCities=0;
    }

    public void addCity(String city){
        this.city[this.numberOfCities]=new City(city);
        this.numberOfCities++;
    }

    public String toString(){
        String cityDetails=new String();
        if (this.numberOfCities!=0){
            cityDetails+=String.format("%-15s\n","CITY");
            for(Integer i=0;i<this.numberOfCities;i++)
            cityDetails+=this.city[i]+"\n";
        }
        else
            cityDetails+="City list is empty";
        return cityDetails;
    }

    public void sort(){
        int j, i;  
        for(i =1; i < city.length; i++){    
            City temp = city[i];           
            j = i;                
            while((j>0) && ((city[j -1].getCity().compareTo(temp.getCity()))>0)){               
                city[j] = city[j-1];
                --j; 
            }    
            city[j] = temp;    
         }
     }
}

1 个答案:

答案 0 :(得分:0)

在for循环i < city.length && city[i] != null中添加一个条件,以便在数组未满时停止。 java中的数组也是基于0的,即第一个元素是city[0]而不是city[1]