What does the name of an object in Java mean (array, ArrayList)

See English answers > java arrays printing out weight numbers and text 10

ArrayList<Integer> myList = new ArrayList<Integer>();

     for(int j = 0 ; j < 10 ;j++){

          myList.add(j);
    }

    System.out.println(myList);

  the o/p is:
            [0,1,2,3,4,5,6,7,8,9]

According to my understanding, I have an ArrayList object (mylist) here

Now I try to do the same with the array object: the same code, but replace the ArrayList with an array:

int [] Arr = new int[]{1,9,10};

    System.out.println(Arr);

I got the garbage value Why is that? What is the difference between array and ArrayList? As in C, the name of an array is a pointer (it has the address of the first element), so what does the name of an object mean in Java? Address or reference? Any difference? Why do you get different results in the case of array and ArrayList?

Solution

In Java, the name of a variable is a reference to the variable (if we compare it with C) When you call println in mylist, you actually call the toString () method of ArrayList, which inherits from object but is overwritten to provide meaningful printing This method inherits from object, because ArrayList is a class and all classes extend object, so it has toString method

You don't have a native array. This feature is a primitive, so you get the default object representation (virtual memory address)

You can try something like this:

public class TestPrint {
    private String name;
    private int age;

    public TestPrint(String name,int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name;}

    public int getAge() { return age; }
}

Then try println (New testprint ("test", 20)); – This will print something similar to what you use an array

Now, add a toString () method:

@Override
public String toString() {
  return "TestPrint Name=" + name + " Age=" + age;
}

And call println (New testprint ("test", 20)); Again, you will get testprint name = test age = 20 as the output

Just to further explain why this happens - the method println has an overload that accepts the object type The implementation of this method calls toString to print the object (of course, this is a very schematic explanation)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>