User definded object in ArrayList - Generics Example

Here, we are going to create a list of user defined object type. First of all we can create a java object with some sample fields and getters and setters methods along with overridden toString method.

package com.amzi.examples;

public class User {

    private String userName;
    private String password;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public String getPassword() {
        return password;

    public void setPassword(String password) {
        this.password = password;

    public String toString() {
        return "User [userName=" + userName + ", password=" + password + "]";

Now, we are going to write a java class which will create a list of this user object and will see various list methods.

package com.amzi.examples;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample1 {

    public static void main(String[] args) {

        // initializing user object with some sample data
        User user1 = new User();

        User user2 = new User();

        // initializing list object of type User
        List<User> list = new ArrayList<User>();

        // adding user object into the list

        System.out.println("Printing user1 elements: " + user1);

        System.out.println("Printing list object: " + list);

        // looping through the userObject and list
        for (User u : list) {
            System.out.println(u.getUserName() + "\t--  " + u.getPassword());


Printing user1 elements: User [userName=Amzi, password=password1]
Printing list object: [User [userName=Amzi, password=password1], User [userName=Saiyad, password=password2]]
Amzi    --  password1
Saiyad    --  password2

1 comment:

  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    or learn thru JavaScript Online Training from India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.