Using ArrayList with Bean in Java

First let us know about Beans in Java. Java Bean is a normal Java class which has private properties with its public getter and setter method. Java Beans are generally used as helper class.

Example:

public class StudentBean { 
private String name; 
public void setName(String name) 
    { 
        this.name = name; 
    } 
public String getName() 
    { 
        return name; 
    } 
} 

In the above example, I have created a Bean class StudentBean with private property name. A setter method setName is used to update value of a variable and a getter method getName retrieves value of a variable.

Now let's create a Bean class called HelperBean to create arraylist of Beans. 

public class HelperBean {
    private ArrayList<StudentBean> StudentList;

    public void setStudentList(ArrayList<StudentBean> StudentList) {
        this.StudentList = StudentList;
    }

    public ArrayList<StudentBean> getStudentList() {
        if (StudentList == null || StudentList.size() == 0) {
            StudentList = new ArrayList<StudentBean>();
        }
        return StudentList;
    }
}

In the above example, I am adding the Bean StudentBean to the arraylist. It is same as normal Bean but the difference is we are storing and retrieving the data from arraylist. I have created a private property StudentList for the StudentBean ArrayList. setStudentList is the setter method to store the array of StudentBean. getStudentList is the getter method to retrieve the array. While retrieving check the size of the ArrayList variable. If the size of the arraylist = 0, then create the new arraylist and return it.

Adding data into Bean Array:

In the Model(DAO), create a method DisplayRecords of the type HelperBean to fetch all the names from the table sookshmas and add it into HelperBean.

public HelperBean DisplayRecords() {
        HelperBean hbean = new HelperBean();
        try {

            ResultSet rs = null;
            Statement statement = null;
            statement = (Statement) con.createStatement();
            String Query = "select * from sookshmas;";
            rs = statement.executeQuery(Query);
            while (rs.next()) {
                StudentBean cbean = new StudentBean();
                cbean.setName(rs.getString("name"));
 		cbean.setEmail(rs.getString("email"));
 		cbean.setPhone(rs.getString("phone"));
                hbean.getStudentList().add(cbean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hbean;
    }

Create an object for HelperBean class by using HelperBean hbean = new HelperBean();.

Write the query and execute it. If the query returns the result, Create an object for the StudentBean class. Store the data by using the setter methods of StudentBean class. After 1 record is stored in StudentBean class, add that into arraylist by using HelperBean object hbean.Then again loop it till all the records are fetched nd keep storing all the StudentBean object in the arraylist.After fetching all the records return the HelperBean object hbean.
To simplify this, consider 10 records are there in sookshmas table.Then 10 StudentBean objects are created and added into 
HelperBean class i.e, HelperBean contains 10 StudentBean objects.

Retrieving data from java bean and store in JSONArray:

In the Controller(Handler) , create an object for JSONArray and JSONObject .

JSONObject json1 = new JSONObject();
JSONArray array = new JSONArray();

HelperBean hbean = a.DisplayAnnouncement();
if (hbean.getStudentList.size() > 0 && hbean.getStudentList != null) {
for (int i = 0; i < hbean.getStudentList().size(); i++) {
StudentBean cbean = hbean.getStudentList().get(i);
JSONObject json = new JSONObject();
 json.put("name", cbean.getName());
 json.put("phone", cbean.getPhone());
 json.put("email", cbean.getEmail());
 array.put(json);
}
json1.put("jsonarray", array);
out.print(json1);
}

Call the method DisplayRecords() and store the result in Helperbean object hbean(bcoz the return type of the method is HelperBean). Check the size of the hbean. If it is greater than 0 then loop it till the condition become false. 

CommonBean cbean = hbean.getStudentList().get(i);

Fetch the ith value of the record from the array and store it in cbean object. Create json object . Fetch the data from the StudentBean object and put it in json object. Put the ith json data into array.After the iteration is completed, put the array object in another json object json1. Then print that json1 object value.

The output of json1 will be:

{"name": abc, "phone":1234562514, "email":[email protected]}

This json1 object can be used in frontend to display the value which will be explained later.

JSONObject: JSONObject is an unordered collection of key and value pairs, resembling Java's native Map implementations. 

json.put("name", cbean.getName()); Here name is the key and cbean.getName() will be the value.

Posted on by