Create an ArrayList with multiple object types?

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

    You can use Object for storing any type of value for e.g. int, float, String, class objects, or any other java objects, since it is the root of all the class. For e.g.

    1. Declaring a class

      class Person {
      public int personId;
      public String personName;
      
      public int getPersonId() {
          return personId;
      }
      
      public void setPersonId(int personId) {
          this.personId = personId;
      }
      
      public String getPersonName() {
          return personName;
      }
      
      public void setPersonName(String personName) {
          this.personName = personName;
      }}
      
    2. main function code, which creates the new person object, int, float, and string type, and then is added to the List, and iterated using for loop. Each object is identified, and then the value is printed.

          Person p = new Person();
      p.setPersonId(1);
      p.setPersonName("Tom");
      
      List lstObject = new ArrayList();
      lstObject.add(1232);
      lstObject.add("String");
      lstObject.add(122.212f);
      lstObject.add(p);
      
      for (Object obj : lstObject) {
          if (obj.getClass() == String.class) {
              System.out.println("I found a string :- " + obj);
          }
          if (obj.getClass() == Integer.class) {
              System.out.println("I found an int :- " + obj);
          }
          if (obj.getClass() == Float.class) {
              System.out.println("I found a float :- " + obj);
          }
          if (obj.getClass() == Person.class) {
              Person person = (Person) obj;
              System.out.println("I found a person object");
              System.out.println("Person Id :- " + person.getPersonId());
              System.out.println("Person Name :- " + person.getPersonName());
          }
      }
      
      
      
      

      You can find more information on the object class on this link Object in java

      提交回复
      热议问题