If attribute is really one of your class member then please use as follow.
((Ticket) list.get(index)).attribute;
Question
I am working with an ArrayList
of objects that contain multiple variables. For example:
// pseudo code
class Ticket {
int gameID
double price
int seatnumber
}
and I have an ArrayList
of multiple Ticket
objects and need to access them. I've looked at the javadoc and so far I have come up with
list.get(index).attribute
However I get a compile-error saying:
cannot find symbol
am I doing something wrong with the syntax? here is my code:
public static void printGameMoney(ArrayList games, ArrayList tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
Solution 2
If attribute is really one of your class member then please use as follow.
((Ticket) list.get(index)).attribute;
OTHER TIPS
You code is "old-school", you should use typed-types, interfaces and new style for-loop:
public static void printGameMoney(final List<Game> games, final List<Ticket> tickets)
{
double total = 0;
for (final Ticket ticket : tickets)
{
final double tickMoney = ticket.getPriceOfTick();
total = total + tickMoney;
}
}
Also note this method is strange as it doesn't return anything.
Start by putting semicolons after each field declaration:
class Ticket {
int gameID;
double price;
int seatnumber;
}
Also, show the exact code you're using instead of list.get(index).attribute
.
List<Object> list = new ArrayList<Object>();
((Ticket)list.get(x)).attribute;
Use this instead:
public static void printGameMoney(ArrayList games, ArrayList<Ticket> tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
Basically, the change leads to ArrayList<Ticket>
instead of simple ArrayList
. This way you tell the compiler that objects inside your ArrayList
are of Ticket
type, therefore they have attributes you specified (e.g. priceOfTick
).
Same goes for games
, so if you have Game
class, you should use ArrayList<Game> games
.
You have to access like this ,list.get(i).price;
not list.price.get(i);
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = list.get(i).price;
total = total + tickMoney;
}
Here problem is that with your deceleration of ArrayList
If you declare like ArrayList<Ticket>
you need not to cast there while getting. Other wise you need a cast there. More over use for each loop.