Question

I am switching over from C to java programming gradually. While doing so I am confused while understanding the following scenario: I have following Java Code:

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 what I have here is an object(myList) of type ArrayList.

Now I tried to do the same with an Array object: The same code but replacing Arraylist with an Array:

  int [] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};

    System.out.println(Arr);

I get Garbage values. Why is this so? What is the difference between Array and ArrayList? As in C , the name of the array is sort of a pointer. (IT has the address of the first element) , So in Java , what does the mere names of the object imply ? Address or Reference ? What is the difference? Why do I get varied results in case of Array and ArrayList?

Was it helpful?

Solution 2

In java, a name of a variable is a reference to the variable (if we compare to c++). When you call println on myList you in-fact call the toString() method of ArrayList which is inherited from Object but overridden to give meaningful print. This method is inherited from Object because ArrayList is a class and all classes extend Object and thus have the method toString.

You don't have this trait with native arrays which are primitives so what you get is 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 got with the array.

Now, add a toString() method:

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

And call println(new TestPrint("Test", 20)); again and you'll get TestPrint Name=Test Age=20 as the output.

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

OTHER TIPS

Although all parts of the question have been answered in different posts, I'd like to address your specific wording.

First, it is recommended that you declare your list type as an interface and initialize it as an implementation:

List<Object> list = new ArrayList<Object>();
List<Object> list = new ArrayList<>(); // JDK 7 or later allows you to omit the generic type.

You can implement a List interface with several implementations (ArrayList, LinkedList...). See the collection tutorial.

What is the difference between Array and ArrayList?

ArrayList is a class, see the API. it serves as an implementation for the List interface, see the API. These are part of the Java Collections Framework.

An array is not a class as the ArrayList is, but both an array and an instance of a class are objects. Be careful with uppercasing Array, as it is a different class.

I get garbage values. Why is this so?

Why do I get varied results in case of Array and ArrayList?

This has to do with the println method. It automatically calls the toString method of the argument passed into it. The toString method is defined for the Object class which superclasses all other classes, thus they all inherit it. Unless the subclass overrides the inherited method, it retains the implementation of its superclass. Let's look at what it does for Object:

public String toString()

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Emphasis mine. As you can see, that's the "garbage" you get when printing the array variable. Since arrays are not classes, they cannot override this method (arrays can invoke all the methods of Object, although they don't subclass it in the usual way). However, the subclass AbstractCollection of Object overrides this:

public String toString()

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

Since ArrayList is a subclass of AbstractList, which is a subclass of AbstractCollection (and they do not override toString), you get the "concise but informative representation that is easy for a person to read".

There are some fine points as to how the JVM handles arrays, but for the sake of understanding the output from the developer's point of view, this is enough.

In Java everything is a pointer, but depending on what a variable is pointing, the behavior can change.

int[] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};

int[] is an array of a primitive type (not of a class type), and it does not contains any information about its 'string representation', so when you want to print the variable as you have done (System.out.println(Arr);), what is printed out it is simply a string representation suitable for any kind of object, like its hashcode (it is not garbage).

While with:

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

you are creating an object of the (generic) class ArrayList<>: this overrides the method (function in C) toString() that specify how print gracefully the content of the ArrayList itself (the method is really basic: it simply iterate over all the items contained, create a string and print it).

When you call System.out.println(myList); the method toString() (which return a String) is implicitly called, and therefore the string created by the method will be printed, as you have shown.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top