Create an ArrayList with multiple object types?

前端 未结 12 2592
抹茶落季
抹茶落季 2020-12-08 01:57

How do I create an ArrayList with integer and string input types? If I create one as:

List sections = new ArrayList 

        
12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 02:30

    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 al=new ArrayList();
            al.add(s1);
            al.add(s2);  
            al.add(s3);  
    
            Iterator itr=al.iterator();  
    
            //traverse elements of ArrayList object  
            while(itr.hasNext()){  
                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){  
            this.rollno=rollno;  
            this.name=name;  
            this.age=age;  
        }  
    } 
    

    Program Output:

    1 AAA 13

    2 BBB 14

    3 CCC 15

提交回复
热议问题