0

I am working with Java8, and I want to know the internal working of ArrayList printing. like if I run my below program, it will give object reference and will not print all of its data members values.

public class Hello{

    int a = 1;
    int b = 2;
    
     public static void main(String []args){
        Hello h = new Hello();
        System.out.println(h.a);
        System.out.println(h.b);
        System.out.println(h);
     }
}

Output : 1 2 Hello@2a139a55

And if I use ArrayList it won't print references and will directly print values

import java.util.ArrayList;
public class Hello{

     public static void main(String []args){
        ArrayList<String> name = new ArrayList<>();
        name.add("Monday");
        name.add("Tuesday");
        
        System.out.println(name);
     }
}

Output: [Monday, Tuesday]

Can you please explain how it is working internally is it dereferencing it like in C language and my second question is how I can implement something similar using object + print in Java?

I read other articles on net on how to print ArrayList using for loop, for each loop and using iterator but none of them accurately specifies how does direct mention of object in print statement returns its values rather than reference.

  • a bit of googling could have helped you here: https://developer.classpath.org/doc/java/util/AbstractCollection-source.html The toString method in this class is inherited by (among others) ArrayList – Stultuske Nov 10 '22 at 07:38
  • @Chaosfire his inquiry is to what the toString does. – Stultuske Nov 10 '22 at 07:39
  • @Stultuske I am not so sure, `Can you please explain how it is working internally is it dereferencing it like in C language and my second question is how I can implement something similar using object + print in Java?` - sounds like exact duplicate to me, OP never mentions `toString()` in question. I think linked question answers both of his questions. – Chaosfire Nov 10 '22 at 07:47
  • Thankyou @user16320675 and everyone my doubt is resolved. – Aakash Rohila Nov 10 '22 at 08:20

0 Answers0