Dakshila Kamalsooriya Dakshila Kamalsooriya - 10 months ago 67
Java Question

Create an arraylist with multiple object types?

How do i create an arraylist with integer and string input types? If i create as

List<Integer> sections = new ArrayList <Integer>();

that will be a Integer type arrayList.
If i create as
List<String> sections = new ArrayList <String>();
that will be String type.
How can i create an arraylist which can take both int and String input types?
Thank you

Answer Source

User Defined Class Array List Example

import java.util.*;  

public class UserDefinedClassInArrayList {

    public static void main(String[] args) {

        //Creating user defined class objects  
        Student s1=new Student(1,"AAA",13);  
        Student s2=new Student(2,"BBB",14);  
        Student s3=new Student(3,"CCC",15); 

        ArrayList<Student> al=new ArrayList<Student>();

        Iterator itr=al.iterator();  

        //traverse elements of ArrayList object  
            Student st=(Student)itr.next();  
            System.out.println(st.rollno+" "+st.name+" "+st.age);  

class Student{  
    int rollno;  
    String name;  
    int age;  
    Student(int rollno,String name,int age){  

Program Output:

1 AAA 13

2 BBB 14

3 CCC 15