-3

I am making an inventory program in java, I need to getItem from the index. I am a bit confused how to return the item from the index.

  • What have you tried so far? Are you trying to get it from an array or an actual ArrayList? What does your code look like? – Orin Jun 03 '16 at 16:47
  • 1
    @Orin2005 *"What does your code look like?"* See the edit history. OP posted the code, but removed it later. – Tom Jun 03 '16 at 17:06

2 Answers2

1

This is the easiest method yet! If you simply want to retrieve the item by position, then ArrayList#get is your method. Per the Oracle docs,

Returns the element at the specified position in this list.

public StockItem getItem(int index) {
    return this.stock.get(index);
}

However, you have to add in the special case for the null return specified by your JavaDocs. There are two ways to do this

First way

public StockItem getItem(int index) {
    if (index < 0 || index >= this.stock.size()){
        return null;
    }
    return this.stock.get(index);
}

Second way

public StockItem getItem(int index) {
    try{
        return this.stock.get(index);
    }catch(IndexOutOfBoundsException e){
        return null;
    }
}

I'd suggest the first way because, although there is additional logic, using Exceptions as regular control flow in your code is not good practice. See this and this for more discussion.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michael
  • 2,673
  • 1
  • 16
  • 27
1
public StockItem getItem(int index) {
     try
     {
         return stock.get(index)
     }
     catch(IndexOutOfBoundsException ex)
     {
         return null;
     }
}
Hendri
  • 111
  • 2
  • 1
    Exceptions should not be used like this, you should check that the index is valid instead. – explv Jun 03 '16 at 16:42