所以我有一个正在从文本文件中读取的国家/地区列表,其中一些国家/地区不止一次出现在该列表中。我需要将每个国家/地区名称放入字符串数组中,不带任何 double ,或者将国家/地区名称放入其中两次。我尝试使用 for 循环,但无法理解所需的逻辑。
提前致谢。
最佳答案
尝试使用Set
。集合可以包含一个但不超过一个特定实例(instance1.equals(instance2)
不会是 true
)。
像这样实例化一个Set
:
Set<String> s = new HashSet<String>();
然后使用 for 循环添加值。
String[] countries = {"JP", "US", "CN", "RU", "RU"}; //just make pretend these were read from a file.
for (String countryName: countries){
s.add(countryName); // RU will only be added once
}
System.out.println(s);
输出:[日本、美国、俄罗斯、中国]
关于java - 仅将唯一值放入数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22102103/