Question about linked list of objects

Debugging

Hi

so im designing an airline reservation system, and I'm trying to collect user input to act as public attributes for my passenger object. these passenger objects are in a linked list called PassLL. im trying to print out this linked list. here's the code:

import java.util.*;

​

class Main {

public static void main(String[] args) {

//initialization of passenger LL

LinkedList<Passenger> PassLL = new LinkedList<Passenger>();

​

System.out.println("Welcome to the airline reservation system.");

//passenger input

Scanner input = new Scanner(System.in);

System.out.println("Please enter your full name: ");

String fullName = input.nextLine();

​

Scanner input2 = new Scanner(System.in);

System.out.println("Please enter your DOB in ddmmyyyy format: ");

int DOB = input2.nextInt();

​

Scanner input3 = new Scanner(System.in);

System.out.println("Please enter your passport nationality: ");

String nationality = input3.nextLine();

​

Scanner input4 = new Scanner(System.in);

System.out.println("Please enter your passport number: ");

int ppNum = input.nextInt();

//the instantiation of a passenger, and the attributes attached to

//each passenger

PassLL.add(new Passenger(fullName, DOB, nationality, ppNum));

​

System.out.println(PassLL);

​

upon running this, it prints out:

[Passenger@682a0b20]

why?

Posted Feb 25, 2022, 12:12 PM UTC

11
fredoverflow•

If you print an object, its toString() method is called. LinkedList<Passenger>.toString calls Passenger.toString, which you did not override, so Object.toString is called, which simply prints the class name followed by the hashCode. You need to override Passenger.toString() to return a string containing whatever information you want to see instead:

class Passenger {
    // ...
    @Override
    public String toString() {
        return "a suitable string representation of Passenger";
    }
}
2