Storing Java Object In LinkedList

Earlier we have read LinkedList in Java and how to create LinkedList in Java , i you are new LinkedList then i recommenced to you first read this tutorials. In This tutorial we will see how to adding objects to a linked list java . We will create one java pojo class and linkedlist of this object type . I means we will create linked list of objects  in java . Then we create object this class and store these object in linkedlist , Let’s see this by code

import java.util.LinkedList;

public class LinkedListOfObject {

public static void main(String[] args) {

LinkedList<User> list = new LinkedList<User>();
list.add(new User("Yogesh",123));
list.add(new User("Shivam",123));
list.add(new User("Amit",123));
list.add(new User("Sunder",123));

for (User user : list) {
System.out.println("user name="+user.getName()+"  user Id="+user.getEmpId());
}

}
}

class User{
private String name;
private int empId;

public User(String name, int empId) {
super();
this.name = name;
this.empId = empId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}

Output:

user name=Yogesh user Id=123

user name=Shivam user Id=123

user name=Amit user Id=123

user name=Sunder user Id=123

A Guide To LinkedList

 

Leave a Reply

Your email address will not be published. Required fields are marked *

58 + = 60