简体   繁体   中英

How to display java bean objects in a container without using get() in a loop?

I'm new to java. can you guide me on the below snippet. I have added 5 EmpBean objects to the ArrayList arr.

 List arr=new ArrayList();
    for(int i=0;i<5;i++)
    {
        EmpBean eb=new EmpBean();
        eb.setFirstID(i);
        eb.setLastID(i);
        arr.add(eb);
    }

How do I display those 5 EmpBean objects in a single shot and not by using arr.get(0) and display individual EmpBean objects?

please help,

Thanks

You need to loop over your ArrayList in order to print its value:

Example

for (EmpBean bean: arr) {   
    System.out.println(bean.toString());
}

To override toString method in your class, you can do something like this:

@Override
public String toString() {
    return String.format("First id : %s, Second Id : %s", getFirstID(), getSecondID());//suppose you have a getter's for these variables.
}

You can iterate through your list with a for loop.

for (EmpBean empBean : arr)
{
    //do stuff with your empBean instance
}

or

for (int i = 0; i < arr.size(); i++)
{
    EmpBean empBean = arr.get(i);
    // do stuff with you empBean
}

To display all object in single shot just print the arr object

System.out.println(arr)

Because List already override toString() method to display all it's elements in angular brackets [elements.]

To display each element use foreach loop.

If it's a primitive type List then you can get all the elements when you print the list itself, but incase of List<Object> you won't able to display the contents like that. In that case you have to use either a loop or an iterator:

1.

List<EmpBean>list = new ArrayList<EmpBean>();   
for (EmpBean ob:list) {   
    //do stuff with o   
}  

2 .

List<EmpBean>list = new ArrayList<EmpBean>();   //you need to populate this list
Iterator iter = list.iterator();   

while (iter.hasNext()) {   
    Object o = iter.next();   
    //do stuff with o   
}  

come on guys for loop is soo java7, let's be up-to-date :D

    arr.stream().forEach(a -> System.out.println(a));
  • redefine toString in EmpBean to whatever you want to display :)

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