Yousaf Yousaf - 14 days ago 5
Java Question

Adding data of different type and from different class in Arraylist

So i have recently started learning java and currently studying Array List.

Suppose that i have two classes A and B. In class A i have two attributes which are string type 'name' and int type 'age'.

In class B i have an array list and what i want to do is add the value of name and age in the array list.

How can i do that and also how can i add different type of data in one Array list ?
Following is the code in the two classes that i have written but compiler gives error.

public class A {

public String name;
public int age;

public input()
{
name = "ALI";
age = 20;
}

}

public class B{

A obj = new A();
ArrayList aa = new ArrayList(); //error here

aa.add(obj.name); //error here

}

Answer

Your code snippet was not much clear. I assume that your are trying to do this.

import java.util.ArrayList;

class ClassB {

public String name;
public int age;

public ClassB() {
    name = "ALI";
    age = 53;
}

}

public class ClassA {

public static void main(String[] args) {

    ClassB obj = new ClassB();
    ArrayList aa = new ArrayList();

    aa.add(obj.age); // int
    aa.add(obj.name); // string

    aa.add(15.2); // float
}

}

If you notice that float is also added in arraylist. As you want to add other data type. As long as you have not specified any specific generic data type to any of collection classes. You can add any data type.