Abhishek Kumar Abhishek Kumar - 2 months ago 6x
Java Question

Display Class member value using ArrayList of Objects

I am new to java and android. I have created a class with definition below :

public class MyClass {
int id;
String name;

Now I am creating objects of class, initializing value to class members and adding objects to array list like this :

MyClass myclassobj1 = new MyClass();
myclassobj1.id = 1;
myclassobj1.name = "Abhishek";
MyClass myclassobj2 = new MyClass();
myclassobj2.id = 2;
myclassobj2.name = "Kumar";

ArrayList<MyClass> taskList = new ArrayList<MyClass>();

Now I assign arraylist to iterator like this

Iterator it = taskList.iterator();

Now when I iterate over array list I want to Log the values I added to class members, which I am not able to do

while (it.hasNext())

Please help


you should do something like this instead:

List<MyClass> taskList = new ArrayList<MyClass>();
taskList.add(new MyClass(1, "kumar1"));
taskList.add(new MyClass(2, "kumar2"));

the in the class MyClass define the constructor with parameters...

AND override the toString Method in the class so you can see something human-readable when you print the object...

having done this, you will see how this will work:

for (MyClass mx: taskList) {
    Log.d(TAG, mx.toString());

an example of how the MyClass can look like this:

class MyClass {
    private int id;
    private String name;
    public MyClass(int id, String name) {
    this.id = id;
    this.name = name;
    public String toString() {
    return "MyClass [id=" + id + ", name=" + name + "]";



I suspect you want the iterator to get the values hold in the List and not the name of the field...

the implementation looks like:

Iterator<MyClass> it = taskList.iterator();
while (it.hasNext()) {

you will need for sure the respective getters...

public int getId() {
    return id;
public String getName() {
    return name;