hteeT
hteeT

Reputation: 3

Java: Can't add an int to an arraylist

I've created an empty arraylist here:

private ArrayList<OrderItem>  conveyorBelt = new ArrayList<OrderItem>(10);

And in the same class, I've created a method where I add item into the conveyorBelt by inputting the orderNum (which is an int). This is what the method looks like:

public void addToConveyorBelt( int orderNum )
{
OrderItem oi;
conveyorBelt.add(oi.getOrderNum(orderNum)); // line 4
}

This doesn't work. I get a compile error on line 4, saying this: http://i52.tinypic.com/ny8n86.jpg

Anyone know where i'm going wrong with this?

p.s. - the OrderItem contains one variable called theOrderNum and a method that calls it called getOrderNum.

Upvotes: 0

Views: 1585

Answers (4)

user467871
user467871

Reputation:

you define arraylist like that

private ArrayList<OrderItem>  conveyorBelt = new ArrayList<OrderItem>(10);

It means you can only add OrderItem to the list

public void addToConveyorBelt( int orderNum )
{
OrderItem oi;
conveyorBelt.add(oi.getOrderNum(orderNum)); // here it fails
}

Change it as follows

public void addToConveyorBelt( int orderNum )
    {
    OrderItem oi = new OrderItem(orderNum);
    conveyorBelt.add(oi); // here it fails
    }

oi.getOrderNum(orderNum) should throw NullPointerException

Upvotes: 0

Brett Kail
Brett Kail

Reputation: 33946

According to the error message, the method signature of "getOrderNo" does not accept a parameter of type "int". From what you've given, I suspect the OrderItem class looks something like this:

public class OrderItem {
    private int theOrderNum;

    OrderItem(int num) {
        theOrderNum = num;
    }

    public int getOrderNum() {
        return theOrderNum;
    }
}

If so, you want to create a new OrderItem from the orderNum parameter, and then add it to conveyerBelt:

public void addToConveyorBelt(int orderNum) {
    OrderItem oi = new OrderItem(orderNum);
    conveyorBelt.add(oi);
}

If not, you need to update the question to include more information about the OrderItem class.

Upvotes: 3

Robert
Robert

Reputation: 8609

I suspect your method should be something like this:

public void addToConveyorBelt(int orderNum){
    OrderItem oi = getOrderItem(orderNum);
    conveyorBelt.add(oi); 
}

Upvotes: 1

Falmarri
Falmarri

Reputation: 48577

getOrderNum obviously returns an int. Your arraylist is an arraylist of OrderItems. What are you expecting to happen?

Not only that, but you're guarunteed a null pointer exception there because oi isn't initialised.

Upvotes: 1

Related Questions