创建Set
// Create new Set
Set<City> cities = new HashSet<City>();
// Add new City
cities.add(new City());
将 Set 转换为数组 - 选项 #1
City[] objects = cities.toArray(new City[0]);
将 Set 转换为数组 - 选项 #2
手动复制:
City[] objects = new City[cities.size()];
int position = 0;
for (City city : cities) {
objects[position] = city;
position++;
}
工作示例
public class SetExample {
private static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
Set<City> cities = readCities();
}
private static Set<City> readCities() {
Set<City> cities = new HashSet<City>();
int numberOfCities = 3;
for (int i = 0; i < numberOfCities; i++) {
City newCity = readCity();
cities.add(newCity);
}
return cities;
}
private static City readCity() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Numbers of citizens: ");
int numbersOfCitizens = scanner.nextInt();
return new City(name, numbersOfCitizens);
}
}
打印
类示例:
class City {
private String name;
private int numbersOfCitizens;
public City(String name, int numbersOfCitizens) {
this.name = name;
this.numbersOfCitizens = numbersOfCitizens;
}
}
当你将使用不添加toString() 方法时:
City city = new City("New York", 1234);
System.out.println(city);
你可以期待输出:
City@19469ea2
要打印自定义消息,您必须重写 toString() 方法,例如在 IntelliJ 中生成“默认”方法:
@Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
", numbersOfCitizens=" + numbersOfCitizens +
'}';
}
或类似的简单的东西:
@Override
public String toString() {
return name + " " + numbersOfCitizens;
}