hamel123 hamel123 - 1 year ago 74
Java Question

ArrayList object to separate Array conversion

I'm stuck on this problem i make a class

in which it has only two properties name and age. I'm taking details of that person as a user input and saving as a object in
but i want to move that
object properties that user enter from keyboard into separate arrays like all names of person into
array and all ages of person into
array from that ArrayList. Is there a way to do that?


public class Person {

String name;
int age;


public class Main {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);
ArrayList<Person> arr = new ArrayList<Person>();
Person person = null;

for(int i=0;i<2;i++){
person = new Person();
System.out.println("Enter Person "+(i+1)+" Record");
int age = 0;
System.out.print("Enter Name : ");
String str = s.nextLine();
person.name = str;
System.out.print("Enter Age : ");
age = s.nextInt();
person.age = age;
person = null;
System.out.println("Record "+(i+1)+" Successful Fill");

String[] stringarray = new String[arr.size()];
int[] intarray = new int[arr.size()];



Answer Source

If you want to hold your arraylist with person-objects and fill the arrays after all values read in create a new function:

private void add2Arrays(List<Person> list) {
  for(int i = 0; i < list.size(); i++) {
    Person p = list.get(i);
    stringarray[i] = p.getName();
    intarray[i] = p.getAge();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download