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.

User.java

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;
    }

    @Override
    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.

ArrayListExample.java

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();
        user1.setUserName("Amzi");
        user1.setPassword("password1");

        User user2 = new User();
        user2.setUserName("Saiyad");
        user2.setPassword("password2");

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

        // adding user object into the list
        list.add(user1);
        list.add(user2);

        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());
        }
    }
}


Output:

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

No comments:

Post a Comment