Home > OS >  How to add element in static list of type object
How to add element in static list of type object

Time:09-15

How to add element in static list of type object.

I have List of Object like this.

List<Object[]> myList = new ArrayList<>();

How can I add static element in that ?

Suppose my element is like

[{
    name : "David",
    roll : "1234",
    class : 5
}]

What I am trying is

static List<Object[]> myList = new ArrayList<>();

myList.add([{
    name : "David",
    roll : "1234",
    class : 5
}])

but this is failing.

CodePudding user response:

You have to write a separate class of that:

For example:

public class User {
  private final String name;
  private final String roll;
  private final int uClass;

  public User(String name, String roll, int uClass) {
    this.name = name;
    this.roll = roll;
    this.uClass = uClass;
  }

  public String getName() {
    return name;
  }

  public String getRoll() {
    return roll;
  }

  public int getuClass() {
    return uClass;
  }

  @Override
  public String toString() {
    return "User{"  
      "name='"   name   '\''  
      ", roll='"   roll   '\''  
      ", uClass="   uClass  
      '}';
  }
}

And then in different classes, you can use it as:

private final ArrayList<User> users= new ArrayList<>();

To add a new User object:

User user1 = new User("David", "1234", 5);
users.add(user1);

CodePudding user response:

[{
    name : "David",
    roll : "1234",
    class : 5
}]

This is not a Java object -- not even a Java object array.

You could add a Java object array, of course.

myList.add(new Object[] {"David", "1234", 5});

...but that's not the object you're looking for. It sounds like you need a class.

  •  Tags:  
  • java
  • Related