-2

I have simple class:

public class Item {

private double price;
private String name; 

public double getPrice() {return Price;}

}

and I have some diffrent objects of Item in the basket:

ArrayList basket = new ArrayList();
basket.add(newItem);

I would like to use something like that to get price:

basket.get(0).getPrice()
basket.get(1).getPrice()

Of course it doesn't work.

michalleek
  • 563
  • 1
  • 4
  • 5

3 Answers3

2
ArrayList basket = new ArrayList();

Two things wrong here:

  • you are using raw types; you should use generics (<= click link for tutorial)
  • the type of basket should not be the implementation type ArrayList, you should program against the interface List

It should look like this:

List<Item> basked = new ArrayList<>();
Community
  • 1
  • 1
Jesper
  • 195,030
  • 44
  • 313
  • 345
1

You can solve it in either of these two ways :

  1. Make the list Item list

    ArrayList<Item> basket = new ArrayList<Item>();

or

  1. Type cast the object before you use them

    ((Item)basket.get(0)).getPrice();

I would prefer the first option.

Community
  • 1
  • 1
Soumitri Pattnaik
  • 2,857
  • 4
  • 22
  • 39
0

Generics.

List<Item> basket = new ArrayList<Item>();
basket.add(new Item());
basket.get(0).getPrice();
betarunex
  • 48
  • 1
  • 10