简体   繁体   中英

How to print the values of the pojo object which is inside an arraylist in java?

I have a requirement where i have to print the values which are getting saved in a database. I have pojo object which i am passing it in a list and then saving the entire list in database. Please find the below code.

List dataList=new ArrayList();
Vehicles vehiclePojoObject=new Vehicles();
vehiclePojoObject.setName("Cycle");
vehiclePojoObject.setColor("Blue");
dataList.add(vehiclePojoObject);

Now i have to print the values which is contained by vehiclePojoObject. How can it be acheived. Please guide. Thanks in advance.

Note : There are not one object but multiple objects which are getting stored in the list.

除了@McMonster 发布的解决方案之外,您还可以确保您的 POJO 覆盖了toString()方法,以便您可以打印自定义的、最有可能的、更具可读性的对象字符串表示形式。

Add vehiclePojoObject to the Vehicles List object, like

List<Vehicles> vehList = new ArrayList<Vehicles>();
Vehicles vehiclePojoObject=new Vehicles();
vehiclePojoObject.setName("Cycle");
vehiclePojoObject.setColor("Blue");
vehList.add(vehiclePojoObject); //Here we are adding pojoObject to list object

And get Vehicles List data through for-each

ie

for(Vehicles vehicle : vehList){
  System.out.println("Vehicle Name: "+veh.getName());
  System.out.println("Vehicle Color: "+veh.getColor());
}

Expanding on @npinti answer of overriding toString()

In your POJO file, add this function:

@Override
public String toString() {
    String output = "Name: " + getName() + " Color: " + getColor +
        " Model: " + getModel() + ....;

    return output;
}

then you can loop through your list to and call .toString() on all the objects to print out all of the features

for(Vehicles vehicle : vehList){
     System.out.println(vehicle.toString());
}

Assuming that you want to store objects of different types on the same list and have a single method for printing all private fields of those object regardless of their types you can use the (reflection API). By the help of reflection we can change behavior of list at runtime

List dataList = new ArrayList<>();

    // Print the name from the list....
    for(Vehicles vehicle: Vehicles) {
        System.out.println(vehicle.getName());
        System.out.println(vehicle.getColor());
    }

Hope this helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM