java - 将字符串插入已排序的数组中

标签 java arrays sorting

我在弄清楚如何让这个程序在 Java 中运行时遇到了一些问题。我应该有一个 WordList 类:

public class WordList{
    private int size; //number of words in array
    private String array1[]; //array of words
    private int capacity; // how big the array is supposed to be

我们应该有两个构造函数: 第一个:

public WordList(int capacity){
    this.array1 = new String[capacity]; //makes a new array of specified capacity
    this.capacity = capacity; //sets the capacity
    this.size = 0; //sets the size of array (i.e. # of words) to 0
}

第二个:

public WordList (String[] arrayOfWords){
    this.capacity = 2 * arrayOfWords.length; //makes the capacity of array twice the # of words in input array
    this.array1 = new String[capacity]; //makes a new array
    this.size = arrayOfWords.length; //sets the # of words in array
    for (int i = 0; i < arrayOfWords.length; i++){ //loops through array
        this.insert(arrayOfWords[i]); //inserts the words (sorted into our array)
}
}

最后是一个插入方法。我认为主要问题就在这里。我不知道我的两个构造函数是否正确,但我 110% 确定这里有问题:

public void insert(String newword){


    for (int i = 0; i < size; i++){
        int l = newword.compareTo(array1[i]);
        if (l > 0)
            continue; // means that the word we're inserting is after
        if (l < 0){
            for (int j = size; j > i; j--){
                array1[j] = array1[j-1]; //shifts all array elements over by one - starting at end of array to avoid over writing anything
            }
            array1[i] = newword;//inserts the word
        }
        if (l == 0)
            return;//doesn't do anything if word is already in list
    }
    }

本质上,它应该将提供的单词插入到已经排序的单词数组中并保持列表排序。程序就崩溃了。关于可能出现问题的任何想法吗?

最佳答案

在 for 循环中,尝试将 j 初始化为 size-1 而不是 size。另外,请注意,虽然如果不检查插入的容量,程序将会运行,但在插入到完整数组时,您将丢失最后一个元素。希望这会有所帮助。

关于java - 将字符串插入已排序的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057992/

相关文章:

java - Magical Number 的省时递归

javascript - 根据表格列中的复选框列表对 html 表格进行排序

java - 在Java中查找hashmap中某个项目的数量

java - ComponentAdapter 中 componentResized 方法的任何替代方法

Java - 通过打开按钮的 Android 对话框

java - 使用随机生成器查找数组中缺失的数字

java - 安全发布数组元素

c++ - 让用户指定数组大小在 XCode 中有效,但在 Visual Studio 中无效

python - 根据规则对python中的列表进行排序

java - 为什么 Java 中没有 SortedList?