Java, thorugh arraylist object invocation methods

Based on this question Variable increment names?

I have an arraylist 'peopleHolder' that contains various 'human' objects. I would like to automatically create person objects based on the for loop. I did the following

peopleHolder.add(new person()); 

I would like to call methods from the person class. e.g. person.setAge; How can I name such methods through the arraist? I would like the method to set values ​​for each object. I looked at this answer: Java are the calling methods of an object located in an ArrayList
But I think the solution depends on calling the static method, and I would like to have a method specific to the object, since they store the value of the objects.

thanks

+4
source share
4 answers

If you want to call a method on all objects from your list, you need to iterate over them first and call the method on each element. Let's say your list looks like this

 List<person> peopleHolder = new ArrayList<person>(); peopleHolder.add(new person()); peopleHolder.add(new person()); 

Now we have two people on the list, and we want to establish their names. We can do it like this:

 for (int i=0; i<list.size(); i++){ list.get(i).setName("newName"+i);//this will set names in format newNameX } 

or using advanced for loop

 int i=0; for (person p: peopleHolder){ p.setName("newName" + i++); } 

By the way, you should adhere to the Java Naming Convention and use the camelCase style. Classes / interfaces / enumerations must begin with an uppercase letter, for example Person , the first token of the variable / method name must begin with lowercase, and others with an uppercase, for example peopleHolder .

+8
source

Is this what you are looking for?

 for(person people: peopleHolder){ people.setAge(25); } 
+3
source

I have several human objects. I automatically create new person objects in the "people" array using a loop. I would like to access methods that define various characteristics of objects (setAge, setHeight, etc.) How can I access such methods for objects that I have? created in my arraylist

Just like you create.

For each person in the list, you can repeat it.

 for(Person person : peopleHolder){ person.setHeight(..); person.setAge(..) } 

For some index in the list, you can use get(int index) , since your list is an arrayList list, and then O (1).

  Person p = peopleHolder.get(someIndex); // where 0 <= someIndex < peopleHolder.size() p.setHeight(..); 
+2
source

Following your code you can do it

 ArrayList<Person> personHolder = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { personHolder.add(new Person()); } // If you want user input, do it in the loop below for (Person p : personHolder) { p.setAge(30); } 
+1
source

Source: https://habr.com/ru/post/1498884/


All Articles