Home > Software design >  Accessing Objects in an LinkedList
Accessing Objects in an LinkedList

Time:03-04

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

The ArrayList(taken from a class named FIFO):

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

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

Thanks beforehand!

CodePudding user response:

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.

CodePudding user response:

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

  • Related