This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Hello everyone i have trouble searching a linked list. Basically I'm reading from a csv file and storing it in the linked list. I was able to add the list at the end. But when i search the list it keep saying it wasn't found. The method function is called contains. A method "contains" that takes a Country object as parameter and checks if the name of the country can be found in the list . to check whether object foo of type Country equals objects bar of type Country, you must override the "equals method" in class Country. When I'm running the code it returns not found and i found out the method contains from class countryNode returns null thats why its returns not found. I will appreciate the help thanks. Everything works except from the contains method. Below is my code:
public Country contains(Country obj)
{
if(this.isEmpty())
{
System.out.println("Sorry this is an Empty list");
return null;
}
else{
CountryNode current = first;
while(current!=null)
{
if(current.getCountry().equals(obj))
{
return current.getCountry();
// break;
}
current = current.getNext();
}
return null;
}
}
The class Country and the overrides method equals:
public class Country {
private String countryNames;
private SubscriptionYear[] subscriptions;
private int size;
private int location;
public Country(String country)
{
this.countryNames = country;
}
public Country(String country, int arraylength)
{
this.countryNames = country;
this.size = arraylength;
subscriptions = new SubscriptionYear[size];
location = 0;
}
public void addSubscriptionYear(int year, double subscription)
{
subscriptions[location]= new SubscriptionYear(year, subscription);
++location;
}
public String toString()
{
System.out.print(countryNames+"\t");
for(SubscriptionYear s: subscriptions)
{
//System.out.print(countryNames+"\t");
System.out.print(s.getSubscription()+"\t");
}
System.out.println();
return "";
}
public String getName()
{
return this.countryNames;
}
public boolean equals(Country obj)
{
return (this.countryNames==obj.countryNames);
}
}
This my test main file:
import java.util.Random;
import java.util.Scanner;
public class TestCountryList
{
/**
* Builds a list of countries to debug.
*/
private void debugListOfCountries(Country [] allCountries)
{
// TO COMPLETE
}
/**
* Builds a random list of countries.
*/
private void testRandomListOfCountries(Country [] allCountries)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many countries do you want to add to the list?");
int requestedSize = keyboard.nextInt();
// Build the list out of a random selection of countries.
Random random = new Random();
CountryList selectedCountries = new CountryList();
for (int i = 0; i < requestedSize; i++)
{
int selectedIndex = random.nextInt(allCountries.length);
selectedCountries.add(allCountries[selectedIndex]);
}
// Note: To debug your list, comment this line in
System.out.println("List of countries: " + selectedCountries);
// Check if the name of a country is in the list.
// If the country is found, print the details.
// Otherwise output not found.
System.out.println("\nWhat country do you want to search for?");
String countryToFind = keyboard.next();
Country obj = new Country(countryToFind);
Country foundCountry = selectedCountries.contains(obj);
if (foundCountry != null)
{
System.out.println("Country " + countryToFind + " found with details:" + foundCountry);
}
else
System.out.println("Country " + countryToFind + " not found.");
}
/**
* Includes test examples for class GraphView.
*/
public static void main(String[] args)
{
// Create and set objects of type Country
//
final String FILENAME = "data/cellular.csv"; // Directory path for Mac OS X
//final String FILENAME = "data\cellular.csv"; // Directory path for Windows OS (i.e. Operating System)
final int NUM_COUNTRIES_TO_TEST = 3; // Note: Include test cases in addition to 3
// Parse the CSV data file
//
CSVReader parser = new CSVReader(FILENAME);
String [] countryNames = parser.getCountryNames();
int [] yearLabels = parser.getYearLabels();
double [][] parsedTable = parser.getParsedTable();
// Create and set objects of type Country
//
Country [] countries;
countries = new Country[NUM_COUNTRIES_TO_TEST];
Country current;
countries = new Country[countryNames.length];
for (int countryIndex = 0; countryIndex < countries.length; countryIndex++)
{
int numberOfYears = yearLabels.length; // OR numberOfYears = dataTable[countryIndex].length;
current = new Country(countryNames[countryIndex], numberOfYears);
for (int yearIndex = 0; yearIndex < numberOfYears; yearIndex++)
{
double [] allSubscriptions = parsedTable[countryIndex];
double countryData = allSubscriptions[yearIndex];
current.addSubscriptionYear(yearLabels[yearIndex], countryData);
}
countries[countryIndex] = current;
}
TestCountryList application = new TestCountryList();
// Note: Initially, to test your output you may hard code the number of
// countries added, and the array positions selected.
// However, make sure to comment this out before submitting your work.
//application.debugListOfCountries(countries);
application.testRandomListOfCountries(countries);
}
}
Try overriding equals method of Object as below:
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (this.countryNames.equals(((Country)obj).countryNames));
}
internally contains call countryList.equals method and equals method's signature is
public boolean equals(Object obj) {}
As opposed to
public boolean equals(Country obj) {}
Also you are just comparing two reference of strings while you need to compare the contents of String. So instead of
this.countryNames==obj.countryNames
You should say:
this.countryNames.equals(obj.countryNames);
you need to use equals or equalsIgnoreCase to compare String
public boolean equals(Country obj)
{
return this.countryNames.equals(obj.countryNames);
}
Related
in Java, I am creating a class, and I would like to keep track of all objects the are created in this class. I have implemented a way to store the names of each object (using ArrayList), but I cannot figure out how to store the object itself in the ArrayList. Here is a snippet of my code:
static public class Ship {
private static ArrayList<String> ships = new ArrayList<String>();
private static ArrayList<Ship> shipObs = new ArrayList<Ship>();
String name;
private ArrayList<String> cruises = new ArrayList<String>();
int maxPassengers;
private static final String[] CABINS = new String[] {"Balcony", "Ocean View", "Suite", "Interior"};
private int[] passengers = new int[] {0,0,0,0};
boolean inService = false;
public Ship(String name, int maxPassengers) {
// Ensure that each ship has a unique name
if (ships.size() == 0) {
this.name = name;
ships.add(name);
}
else if (ships.size() >= 1) {
for (int i=0; i < ships.size(); i++) {
if (ships.get(i).equals(name)) {
System.out.println("Ship "+name+" cannot be created because that name already exists");
return;
}
}
this.name = name;
ships.add(name);
}
this.maxPassengers = maxPassengers;
As you can see, I have the static ArrayList that I would like to populate with all created ships. I assume that this population would take place in the initializing function, but the only method for doing so that I can see would to do something like
shipObs.add(this);
But that doesn't work...
As pointed out in the comments to the question, in addition to the problem asked about, there is another problem: That is, the premature return inside the constructor. Both problems can be addressed by calling the constructor indirectly, through a static method.
import java.util.ArrayList;
public final class Ship {
// private static ArrayList<String> ships = new ArrayList<String>();
private static ArrayList<Ship> shipObs = new ArrayList<Ship>();
String name;
private ArrayList<String> cruises = new ArrayList<String>();
int maxPassengers;
private static final String[] CABINS =
new String[]{"Balcony", "Ocean View", "Suite", "Interior"};
private int[] passengers = new int[]{0, 0, 0, 0};
boolean inService = false;
private Ship(String name, int maxPassengers) {
this.name = name;
// shipObs.add (this);
this.maxPassengers = maxPassengers;
}
public static Ship createAShip(String name, int maxPassengers) {
for (int i = 0; i < shipObs.size(); i++) {
if (shipObs.get(i).name.equals(name)) {
System.out.println("Ship " + name
+ " cannot be created because that name already exists");
return shipObs.get(i);
}
}
Ship theShip = new Ship(name, maxPassengers);
ShipObs.add (theShip);
return theShip;
}
}
I made the constructor private. This prevents client code (code that uses the class) from calling the constructor, forcing use of the static method. But, this disables inheritance. To make it clear that inheritance is not allowed, I added final to public class Ship.
As stated in the comments to the question, a constructor should not return before construction of the Object is complete. If a constructor discovers it cannot be completed, an Exception needs to be thrown.
The static method first checks for a duplicate Ship name. If found, it returns the Ship that bears that name. It would be a good idea to change that part of the code to throw an exception. A third option is to have it return null. Whatever the choice, it should be made clear to users of the class. This can be done using Javadoc.
If a duplicate name is not found, a new Ship is created and returned.
I also simplified the code that checks for a duplicate name. If shipObs.size() returns zero, the for loop is not executed. It is not necessary to guard by enclosing within an if.
I also removed ArrayList<String> ships. Since an Object in shipObs has a name field, ArrayList<String> ships is redundant.
You can't just use a return in the constructor, that would just avoid the next parameter association, you needs to throw an error to stop the instanciation process
If you may need the full objects in a list, track them only with a List<Ship>
You'll the simplified if/else system, you can try to iterate over an empty, it doesn't matter, so just do it
class Ship {
private static List<Ship> ships = new ArrayList<>();
String name;
int maxPassengers;
public Ship(String name, int maxPassengers) {
this.name = name;
for (Ship ship : ships) {
System.out.println(ship + " " + ship.equals(this));
if (ship.equals(this)) {
String msg = "Ship " + ship.name + " cannot be created because that name already exists";
System.out.println(msg);
throw new IllegalArgumentException(msg);
}
}
ships.add(this);
this.maxPassengers = maxPassengers;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Ship ship = (Ship) o;
return name.equals(ship.name);
}
}
If you don't care about the full objects, just use a List<String>
private static List<String> shipNames = new ArrayList<>();
public Ship(String name, int maxPassengers) {
for (String ship : shipNames) {
if (ship.equals(name)) {
String msg = "Ship " + name + " cannot be created because that name already exists";
System.out.println(msg);
throw new IllegalArgumentException(msg);
}
}
this.name = name;
shipNames.add(name);
this.maxPassengers = maxPassengers;
}
The following code will throw the exception at the second line
Ship a = new Ship("ship_1", 10);
Ship b = new Ship("ship_1", 10);
Ship c = new Ship("ship_2", 10);
I would like to convert the following code from array to any other way (the most important is effective) which means that there is infinite space and I will not have to set the length of the array.
How can this be done? How can I set up an unlimited cities? using LinkedList
The idea is that it is possible to define a certain country in which certain cities are stored (the name of the city, the city center, the central bus station,... - as in the picture below) - In my code MAX_NUM_CITIES = 1000;
My Code:
public class Country {
//instance variables
private String _countryName; // name of the country
private City[] _cities; // Array of the cities
private int _noOfCities; //number of cities in a country
public void CityArray() {
_cities = new City[MAX_NUM_CITIES];
_noOfCities = 0;
}
//constants:
public final int MAX_NUM_CITIES = 1000;
/**
* Constructer for object in Country class construct Country with info accordingly
* #param countryName represents the name of country
* #param cities represents the cities array
* #param noOfCities represents the number of cities
*/
public Country(String countryName) {
this._countryName = _countryName;
this._noOfCities = _noOfCities;
City[] cities = new City[MAX_NUM_CITIES];
}
boolean addCity(java.lang.String cityName, double XcityCenter, double YcityCenter, double XStationPoint, double YStationPoint, long numOfResidents, int numOfNeighborhoods) {
if (_noOfCities <= MAX_NUM_CITIES) return false;
_cities[_noOfCities++] = new City(cityName, XcityCenter, YcityCenter, XStationPoint, YStationPoint, numOfResidents, numOfNeighborhoods);
return true;
}
public long getNumOfResidents() {
long SumOfCities = 0;
if (_noOfCities > 0) //empty Array
{
SumOfCities = _cities[0].getNumOfResidents();
for (int i = 1; i < _noOfCities; i++)
SumOfCities += _cities[i].getNumOfResidents();
} else
SumOfCities = 0;
return SumOfCities;
}
public String getCountryName() {
return this._countryName;
}
public int getNumOfCities() {
return this._noOfCities;
}
public City[] getCities() {
int noOfCities = this._noOfCities;
City[] cities = new City[noOfCities];
for (int i = 0; i < _noOfCities; i++) cities[i] = new City(this._cities[i]);
return cities;
}
public String toString() {
if (_noOfCities == 0) //empty Array
System.out.println("There are no cities in this country ");
else
for (int i = 0; i < _noOfCities; i++) _cities[i].toString();
return toString();
}
}
I would step away from arrays if the length is:
unknown
can change
I suggest using one of the different List implementations from the JDK, specifically ArrayList and LinkedList.
The first uses an internal array which may be expanded if an element is added and would lead to the array being too small (it does this all by itself, so no need to worry).
The second is a node list, which means that for every element you add, a new (internal) node object is appended to the last node.
You'd of course have to change your code for this.
Define your _cities to be a List<City>: private List<City> _cities
Initialize that with the wanted implementation in the constructor: _cities = new ArrayList<>(); or _cities = new LinkedList<>();
In your add method you can just call: _cities.add(new City(cityName, XcityCenter, YcityCenter, XStationPoint, YStationPoint, numOfResidents, numOfNeighborhoods));
In your getNumOfResidents you can use the following snippet (which uses Java streaming api introduced in java 8):
return _cities.stream()
.mapToLong(City::getNumOfResidents)
.sum();
for getCities() you'd have to change the return type to List<City> and use the following: return new ArrayList<>(_cities) or return new LinkedList<>(_cities) depending on the implementation you want to use.
I want to create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.
I need to get the input from the user for my "MailCostumer" class.
as you can see there are 3 types: String, int and boolean.
this is the class:
class MailCostumer {
private String name;
private int id;
private String address;
private boolean isPack;
public MailCostumer(String name, int id, String address, boolean isPack) {
this.name=name;
this.id=id;
this.address=address;
this.isPack=isPack;
}
/*in the rest of the class there are the set and get methods
for class fields, if you need to see them, I will post them.*/
My ArrayList is in the class "Queue", like this:
import java.util.ArrayList;
public class Queue
{
private ArrayList<MailCostumer> waiting = new ArrayList<MailCostumer>();
private Boolean isEmpty;
public Queue ()
{
this.waiting = new ArrayList<MailCostumer>();
this.isEmpty=true;
}
public void addClient(MailCostumer MC)
{
this.waiting.add(MC);
this.isEmpty=false;
}
public void delClient(MailCostumer MC)
{
if(waiting.size()!=0)
{
this.waiting.remove(0);
if(waiting.size()==0)
{
this.isEmpty=true;
}
}
}
and this is my main class with the main method:
import java.util.Scanner;
public class Costumer
{
public static void main(String[] args)
{
MailCostumer c1 = new MailCostumer("gabriel", 1234, "ashqelon", true);
MailCostumer c2 = new MailCostumer("tal", 1235, "ashdod", true);
Queue q1 = new Queue();
Scanner scan = new Scanner(System.in);
for(int i=0;i<5;i++)
{
c1.setName(scan.nextLine());
}
q1.addClient(c1);
q1.addClient(c2);
System.out.println(q1.waiting.get(1).getName());
}
}
my question is, how do i get input from the user about different types of data and storing them in my "waiting" ArrayList, as an object of "MailCostumer"?
i need only the ones that isPack==true to be added to the Queue.
im trying to do this from the 'main' method ofcourse, but with no luck.
the 'c1 and c2' i have build, i need the user to input this information.
You can have the user type in a line :
gabriel 1234 ashqelon true
And write your for loop like this (note the extra hasNextLine condition)
This will check that the user typed 4 space separated words and that the last one is "true". In that case it will append a new object to the c1 queue.
for(int i = 0; i < 5 && scan.hasNextLine(); i++) {
String line = scan.nextLine();
String[] data = line.split(" ");
if (data.length() == 4 && "true".equals(data[3])) {
q1.addClient(new MailCostumer(
data[0],
Integer.parseInt(data[1]),
data[2],
true
);
}
}
Third option make a static construction method in MailCostumer that takes a line as argument. That's good design because code specific to generating a MailCostumer object should be packaged in the class and not in main :
public static MailCostumer valueOf(String line) {
String[] data = line.split(" ");
if (data.length() == 4 && "true".equals(data[3])) {
return new MailCostumer(
data[0],
Integer.parseInt(data[1]),
data[2],
true
);
}
return null;
}
The for loop would look very lean then
for(int i = 0; i < 5 && scan.hasNextLine(); i++) {
String line = scan.nextLine();
MailCostumer c = MailCostumer.valueOf(line);
if (c != null)
q1.addClient(c);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is the toString() method being called when I print an object?
I have this piece of code below. I understand everything else except the output using the toString method in the Room Class . In the HotelMain Class, I just called the displayRooms Method that was in the Hotel Class. But, when I ran the program, the toString output was shown in the console.
If I'm right toString() is the textual representation of the value in the object. But, I'm not sure where I called the toString method.
Can someone solve my dilemma? Thank You.
Hotel Class
public class Hotel {
private String hotelName;
private Room[] rooms;
public Hotel(String hotelName, int numberOfRooms) {
this.hotelName = hotelName;
this.rooms = new Room[numberOfRooms];
}
public void addRooms(Room room) {
int position = -1;
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom == null) {
position = i;
break;
}
}
if (position != -1) {
rooms[position] = room;
System.out.println("New room added at postion " + position);
} else {
System.out.println("Addition of room failed.");
}
}
public void displayRooms() {
System.out.println("The Hotel: " + this.hotelName + " has the following rooms.");
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
}
}
Room Class
public class Room {
private int roomNumber;
private int numberOfBeds;
private boolean smokingOrNonSmoking;
public Room() {
}
public Room(int roomNumber, int numberOfBeds, boolean smokingOrNonSmoking) {
this.roomNumber = roomNumber;
this.numberOfBeds = numberOfBeds;
this.smokingOrNonSmoking = smokingOrNonSmoking;
}
#Override
public String toString() {
return "Room [roomNumber=" + roomNumber + ", numberOfBeds="
+ numberOfBeds + ", smokingOrNonSmoking=" + smokingOrNonSmoking
+ "]";
}
}
Hotel Main
public class HotelMain {
public static void main(String[] args) {
Hotel hotel = new Hotel("MahaRani Chain of Hotels", 10);
Room room1 = new Room(4, 2, true);
Room room2 = new Room(2, 1, false);
Room room3 = new Room(6, 3, true);
Room room4 = new Room(6, 4, false);
hotel.addRooms(room1);
hotel.addRooms(room3);
hotel.addRooms(room4);
hotel.addRooms(room2);
hotel.displayRooms();
}
}
Console
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
You have the above code in your displayRooms() method. It prints tempRoom, which is a reference of Room, and hence it calls toString() method overridden in the Room class.
when you call
System.out.println(tempRoom);
the toString() method of Room is automatically called on tempRoom.
In this line
System.out.println(tempRoom);
this is the same as
System.out.println(tempRoom.toString());
toString is a special method of the Object class, here is its description:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
This method is widely used in those places when an object should be converted to textual representation. When you print an object to PrintStream (System.out in this case), this stream calls toString to convert this object to a string.