gpt4 book ai didi

java - 如何将对象按字母顺序插入到ArrayList中?

转载 作者:行者123 更新时间:2023-12-01 19:28:41 26 4
gpt4 key购买 nike

这似乎与这里的其他问题类似,但它有所不同,因为我不想对预先存在的 ArrayList 进行排序。我正在寻找插入对象,当我插入对象时,我检查它是否按字母顺序排列。如果不是,我继续直到 arraylist 的末尾,然后将其添加到 ArrayList 的末尾。

我已有的代码似乎有问题,因为当我运行测试代码时,我的 toString() 方法似乎没有打印任何对象。

import java.util.ArrayList;
import java.util.List;

public class CityDB {
ArrayList<City>cityList = new ArrayList<>();


public ArrayList<City> getCityList(){
return cityList;
}

public void addCity(City city){
for (int i=0; i<cityList.size();i++){
if (cityList.get(i).getName().toLowerCase().compareTo(city.getName().toLowerCase()) == 0){
//city is the same as one of the cities in the list (case insensitive)
//quit the loop (does not store two cities with same name)
break;
}else if (cityList.get(i).getName().toLowerCase().compareTo(city.getName().toLowerCase()) <0 && cityList.get(i+1).getName().toLowerCase().compareTo(city.getName().toLowerCase()) >0){
//city before is lexicographically lesser but city after is lexicographically more (case insensitive)
cityList.add(i+1, city);
//inserts at i+1, which is after the lexicographically smaller city, but is before the city which is lexicographically larger
break;
}else if (i == cityList.size()-1){
cityList.add(city);
}
}
}
}

最佳答案

当您添加第一个城市时,大小为零。你的循环不会被执行。所提供的条件已被破坏

for (int i=0; i<cityList.size();i++){
if (cityList.get(i).getName().toLowerCase().compareTo(city.getName().toLowerCase()) == 0){
//city is the same as one of the cities in the list (case insensitive)
//quit the loop (does not store two cities with same name)
return;
}else if (cityList.get(i).getName().toLowerCase().compareTo(city.getName().toLowerCase()) <0 && cityList.get(i+1).getName().toLowerCase().compareTo(city.getName().toLowerCase()) >0){
//city before is lexicographically lesser but city after is lexicographically more (case insensitive)
cityList.add(i+1, city);
//inserts at i+1, which is after the lexicographically smaller city, but is before the city which is lexicographically larger
return;
}

}
cityList.add(city);

然后您需要修复循环中的条件。第一个条件可以,但考虑第二个条件:

cityList.get(i).getName().toLowerCase().compareTo(city.getName().toLowerCase()) <0 
&&
cityList.get(i+1).getName().toLowerCase().compareTo(city.getName().toLowerCase()) > 0

这不需要分为两部分。首先检查它是否小于当前索引 i,如果小于则将其添加到该索引处。 不检查i+1

关于java - 如何将对象按字母顺序插入到ArrayList中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59281716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com