gpt4 book ai didi

java - 在数组列表中查找唯一元素错误

转载 作者:行者123 更新时间:2023-11-30 06:56:42 25 4
gpt4 key购买 nike

我是数组列表的新手。我有一个计划,我想寻找独特的城市。我使用 for 循环来使用它,但它似乎没有显示我想要的内容。我可以知道我哪里出错了吗?

run:
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Malaysia
Enter size of city: Medium
Enter postal code: 132222
___________________________________________
List Of Unique Cities:
Malaysia,Singapore,Singapore,Singapore,Malaysia,Singapore,
<小时/>

我希望它像这样打印

Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Malaysia
Enter size of city: Medium
Enter postal code: 132222
___________________________________________
List Of Unique Cities:
Malaysia,Singapore,
<小时/>
public class TravellingApp {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

SalesPerson s1 = new SalesPerson();

for(int j=1; j<=20; j++)
{
System.out.print("Enter name of city: ");
String name = sc.nextLine();

System.out.print("Enter size of city: ");
String size = sc.nextLine();

System.out.print("Enter postal code: ");
int postalCode = sc.nextInt();
sc.nextLine();

System.out.println("___________________________________________");



City c1 = new City(name, size, postalCode);
s1.addCity(c1);

}
System.out.println("List Of Unique Cities: ");
for (int i = 0; i < s1.returnListOfCities().size(); i++)
{
for (int k = s1.returnListOfCities().size() - 1; k >= i; k--)
{
if (s1.returnListOfCities().get(i).equals(s1.returnListOfCities().get(k)))
{
s1.returnListOfCities().remove(s1.returnListOfCities().get(i));
break;
}
System.out.print(s1.returnListOfCities().get(k) + ",");

}
}

}

}

最佳答案

您的 City 类必须重写方法 equals() 才能获得您想要的 equals() 行为(默认情况下仅测试对象引用。这种行为不是您想要的)。

顺便说一句,您甚至不需要进行重复检测。只需改用Set接口(interface),就可以保证集合中的所有元素都是唯一的。如果你不关心顺序,那么你可以使用实现HashSet作为实现。因此,实现 City#hashCode() 然后切换到使用此行:

Set<City> s1 = new HashSet<>();

关于java - 在数组列表中查找唯一元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657364/

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