爪哇城市集

时间:2020-11-08 02:36:12

标签: java set

在我的任务中,我已经把一些城市排成一排,但是现在我面临一个问题。

主要是我这样做的:

sort_index

在输入方法城市中,我有3个数组。因此,我需要返回城市名称和公民人数。 在循环中,我输入公民的姓名和人数。在循环结束时,我这样做了:

City[] cities = enterCity(scanner);

,然后与City []个城市一起返回。 现在,我需要使用set改进代码。

在我实现的方法中:

cities[i]=new City(name, numbersOfCitizens);

我无法创建方法添加。我试图用它在main中调用它:

Set<City> cities = new Hashset<>();

在城市类中并返回City []城市说不可转换的类型(因此它不能返回任何内容)。调用方法是正确的事,就像我在main中所做的一样,如果这是如何正确返回所有值的话。在城市课上,我有通常的获取和设置方法。

1 个答案:

答案 0 :(得分:0)

创建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;
}