I
I
Ivan Kuznetsov2016-06-12 17:28:10
Java
Ivan Kuznetsov, 2016-06-12 17:28:10

How to work through ArrayList with own classes?

Good afternoon. My question seems to be a noob one, however, I'm only learning Java and, even googling, I did not find an answer to my question. Please do not throw slippers.
Let's say I wrote my Cat class and added a name variable of type String to it. After that, I created an ArrayList and added some objects. If I had a regular sheet, then using the .get () method, I could easily access and change the value of the variable. But what if I have not only String name declared in my class, but also, let's say int age, how can I refer to a particular variable of a particular cat object. If I had an array Cat[] cats, I could do it like this:
cats[i].name = "name";
And how can I apply in the case of ArrayList?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kornachev, 2016-06-12
@Corrandoo

List<Cat> cats = new ArrayList();
//добавление котов
Cat cat = new Cat();
cats.add(cat);
//....
//получение кота по индексу
int i = 0;
Cat cat1 = cats.get(i);

//так лучше не делать
cat1.name = "имя";

//лучше написать методы setName(String name) для установки имени и getName() для его получения.
cat1.setName("новое имя");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question