Create an ArrayList with multiple object types?

前端 未结 12 2580
抹茶落季
抹茶落季 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:44

    You can just add objects of diffefent "Types" to an instance of ArrayList. No need create an ArrayList. Have a look at the below example, You will get below output:

    Beginning....
    Contents of array: [String, 1]
    Size of the list: 2
    This is not an Integer String
    This is an Integer 1

    package com.viswa.examples.programs;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    
    public class VarArrayListDemo {
    
        @SuppressWarnings({ "rawtypes", "unchecked" })
        public static void main(String[] args) {
            System.out.println(" Beginning....");
    
            ArrayList varTypeArray = new ArrayList();
            varTypeArray.add("String");
            varTypeArray.add(1); //Stored as Integer
    
            System.out.println(" Contents of array: " + varTypeArray + "\n Size of the list: " + varTypeArray.size());
    
            Arrays.stream(varTypeArray.toArray()).forEach(VarArrayListDemo::checkType);
        }
    
        private static  void checkType(T t) {
    
            if (Integer.class.isInstance(t)) {
                System.out.println(" This is an Integer " + t);
            } else {
                System.out.println(" This is not an Integer" + t);
            }
        }
    
    }
    

提交回复
热议问题