user11582989
user11582989

Reputation:

Accessing Objects in an LinkedList

Im trying to create a shopping program where customers are objects assigned with a customer number(given at creation).

Class descriptions. The two classes seen bellow are; Customer and CustomerFactory. The customer class, is being used to create customers (objects) and assigning them with an individual customer number(customerNumber). CustomerFactory is responsible for creating the customers and putting them into an Array.

The Problem. Arises when I try retrieving the customerNumber from respective customer using the getNumber method located in the Customer class. It results in the error: Cannot resolve method 'getNumber' in 'Object', on line 7: ".getNumber". I need to be able to get the customer numbers to, later on, display them as output.

The CustomerFactory class:

1  public class CustomerFactory {
2
3     FIFO f = new FIFO();
4
5     public void createCustomer(){
6        f.add(new Customer(1));
7        f.Q.get(1).getNumber();
8
9     }  
10 }

The Customer class:

1 public class Customer {
2
3    public int customerNumber;
4
5    public Customer(int customerNumber){
6        this.customerNumber = customerNumber;
7
8    }
9
10    public int getNumber(){
11        return this.customerNumber;
12
13    }
14 }

FIFO class:

public class FIFO {

    LinkedList<Customer> Q = new LinkedList<Customer>();

    public Object get(int number){
        return Q.get(number);
    }

    public void add(Customer o){
        Q.add(o);
    }

}

If there are any suggestions on how I can make this problem or anything else that you see more efficient, lmk.

Thanks beforehand!

Upvotes: 0

Views: 67

Answers (2)

AP11
AP11

Reputation: 617

First you are casting the LinkedList as a list containing of Object not Customer (also not sure, why would you use LinkedList, but ok).

LinkedList<Customer> Q = new LinkedList<>();

Then you might be getting NullPointerException, because you are trying to access object with index 1 in this list, but the Customer you create and add to the list Q is on index 0.

public void createCustomer(){
    f.add(new Customer(1, null));
    f.Q.get(0).getNumber();
}

And last but not least, read about Encapsulation, don't just access other class variables by making them public.

Upvotes: 0

Nir Levy
Nir Levy

Reputation: 12953

Your LinkedList should not be of type Object, it should have the generic type of Customer

LinkedList<Customer> Q = new LinkedList<>();

I suggest you'd read a bit about generics in Java, it will help you understand how to handle it better

Upvotes: 0

Related Questions