java - 将字符串按顺序插入数组

标签 java

我有一个已按字母顺序排列的字符串列表。这里我们假设用户按字母顺序输入项目。

我有一个类中的字符串项列表和一个方法,有人可以在其中传入另一个要插入到数组中的字符串对象。

String[] strings = new Strings[0];

public void add(String a){
//here the current list is resized and we need to add the new item
Strings[] newSizedList = new String[strings.length+1];
//for loop here to copy items over into the new resized array.
}

问题是,该列表被假定为已按字母顺序排列。我需要做的是将传入的字符串插入到数组中的正确位置,同时仍保持其他项目按字母顺序排列。

限制是我不想使用任何类型的“排序算法”。换句话说,我不想一次性对整个列表进行排序并按顺序排列。

我想保持项目的顺序,因为它已经按顺序排列,但将当前项目插入到列表中相应的位置。

我无法使用任何 Collection 静态方法或 Java 集合类静态方法

有人知道如何做到这一点吗?

最佳答案

由于无论如何您都将使用 for 循环克隆数组,因此无需在此处进行任何类型的排序(这应该是个好消息,因为您说过这不是一个选项)。只需在浏览项目时将新项目插入到正确的位置即可。

//for loop here to copy items over into the new resized array.
//We use two counters here, ii for the old list and i for the new
int ii = 0, nn = strings.length;
for(int i = 0, n = newSizedList.length; i < n; i++) {

    if(ii != nn && (ii != i || strings[ii].compareTo(a) < 0)){
        //The item in newSizedList[i] will be taken from the original list if
        //we have not already taken all the items from there (ii != nn) and
        //a) we have already inserted the new item (ii != i)
        //or b) a is alphabetically "greater" than the corresponding item in original array
        newSizedList[i] = strings[ii];
        ii++;//Keep the other counter in sync
    } else  {
        //Otherwise, this is the place for the new item
        newSizedList[i] = a;
    }

}

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

相关文章:

Java哲学家餐厅

java - sikuli 1.0.2 文档和 ScreenRegion

java - java 集合的不可修改包装器是否使它们成为线程安全的?

java - 扫描仪跳过输入,可能有空格?

java - 在其中写入一些文本时,文件大小将变为 GB

java - 在 Outlook 中触发外部 API 调用,回复来自特定电子邮件 ID 的电子邮件

java - 将 Java 编译器转换为 Linux

java - 如何 Dockerize Jmeter(使用 Docker 和 Jmeter 进行分布式测试)

java - 无法使用 jpa 更新对象

java - 使用最小堆实现 Dijkstra 算法但失败