8.8k views
2 votes
Create an ArrayList of Countries

- Create a class called Country.java.

- Instance variables include name (String), capital (String), and population (an int representing the population of the capital)

- Write a 3-arg constructor

- Write 3 accessor methods

- Write a toString method that returns the state/value of all instance variables.


- Test out your class:

- Step 1: Create an ArrayList of five countries.

- Step 2: Print out your ArrayList.

- Step 3: Remove one of the countries.

- Step 4: Print out your ArrayList again.

- Step 5: Create a new country and insert it in the middle of your ArrayList.

- Step 7: Print out your ArrayList again.

- Step 8: Change your last country to the country you removed in Step 3.

- Step 9: Print out your ArrayList again.

1 Answer

6 votes

Answer:

Step 1: Create an ArrayList of five countries by creating Country objects and adding them to the ArrayList.

Step 2: Print out your ArrayList by looping through it and printing out each Country object's toString() method.

Step 3: Remove one of the countries from the ArrayList by using the remove() method and passing in the index of the object you wish to remove.

Step 4: Print out your ArrayList again by looping through it and printing out each Country object's toString() method.

Step 5: Create a new country and insert it in the middle of your ArrayList by creating a Country object and using the add() method with the index of the position in the ArrayList.

Step 6: Print out your ArrayList again by looping through it and printing out each Country object's toString() method.

Step 7: Change your last country to the country you removed in Step 3 by first removing the last country from the ArrayList, creating a new Country object using the same parameters as the one you removed earlier, then using the add() method with the index of the last position in the ArrayList.

Step 8: Print out your ArrayList again by looping through it and printing out each Country object's toString() method.

User Adavea
by
8.7k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.