0

In my task I already put some cities in array but I now face a problem.

In main i did this:

City[] cities = enterCity(scanner);

In method enter city I had array of 3. So I needed to return name of a city and number of citizens. In for loop I enter name and number of citizens. At the end of loop I did this:

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

and then returned it with City[] cities. Now I need to improve my code with set.

In method I implemented:

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

I failed to create method add. I tried with this to call it in main:

add.(City(name, numbersOfCitizens));

in City class and return City[] cities says inconvertible types ( so it cannot return anything). Is the right thing to call method like I do in main and if it is how to properly return all values. In class City I have usual get and set method.

Qyz
  • 11
  • 5

1 Answers1

0

Create Set

// Create new Set 
Set<City> cities = new HashSet<City>();

// Add new City
cities.add(new City());

Convert Set in to array - option #1

City[] objects = cities.toArray(new City[0]);

Convert Set in to array - option #2

Manual copy:

City[] objects = new City[cities.size()];
int position = 0;

for (City city : cities) {
    objects[position] = city;
    position++;
}

Working example

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);
    }
}

Printing

Example of the class:

class City {
    private String name;
    private int numbersOfCitizens;

    public City(String name, int numbersOfCitizens) {
        this.name = name;
        this.numbersOfCitizens = numbersOfCitizens;
    }
}

When you will use without adding toString() method so:

City city = new City("New York", 1234);
System.out.println(city);

you can expect output:

City@19469ea2

To print custom message, you have to override toString() method, for example generate "default" method in IntelliJ:

@Override
public String toString() {
    return "City{" +
            "name='" + name + '\'' +
            ", numbersOfCitizens=" + numbersOfCitizens +
            '}';
}

or something simple like:

@Override
public String toString() {
    return name + " " + numbersOfCitizens;
}
Boken
  • 4,825
  • 10
  • 32
  • 42