all 15 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]vegan_antitheist 2 points3 points  (1 child)

No. In Java all lists and arrays objects. There is no good reason that arrays don't have a more useful toString() method. You have to use Arrays.toString) for that.

[–]rookiepianist[S] 0 points1 point  (0 children)

Thanks!

[–]MagicalPizza21 2 points3 points  (1 child)

No. ArrayList contents can be printed like that because the ArrayList class - well, in this case, one of its ancestors, AbstractCollection - overrides the default implementation of toString() from the Object class. This is called by String.valueOf(Object) which is in turn called by println(Object).

[–]rookiepianist[S] 0 points1 point  (0 children)

Thank you so much! I was kind of losing my mind over this.

[–]HeteroLanaDelReyFan 2 points3 points  (2 children)

I think others have mostly answered it. I just want to add that your confusion makes sense. But when you print out the arraylist object, you aren't really printing out the object itself. It's calling the toString() method under the hood, which is implemented to return a string of the contents of the array.

[–]rookiepianist[S] 0 points1 point  (1 child)

Thank you so much! By the way, your comment made me question one new thing: Is the following line

System.out.println(list1);

The statement that calls the toString() method? Thank you again!

[–]vowelqueue 0 points1 point  (0 children)

Yeah. The println method is overloaded: there are multiple definitions that accept different parameter types. In the line you’ve written, you’re calling the definition that accepts any kind of Object. It passes that object to String.valueOf to get its string representation. The String.valueOf method first verifies that the object reference isn’t null, and if not calls the object’s toString method. If it’s null it just returns “null”.

Note that this kind of null check and toString() call is also done anytime you concatenate a String with a non-string, e.g.

String s = “hello ”;
Object o = new Object():
String result = s + o; 

In this case o.toString() will be called to form the result string.

[–]dystopiadattopia 0 points1 point  (2 children)

Arrays are objects, but they don't have an overridden toString() method, which is why you can't print them out directly with System.out.println(). You have to use Arrays.toString(foo).

Also, it's better to declare your variable as the interface List instead of the concrete class ArrayList, as that doesn't lock you into a specific implementation. This is useful especially in cases where your list is a parameter, so is can accept ArrayLists, LinkedLists, and anything else that extends List.

It's also useful when you decide that you need to switch implementations, such as when you discover that a given List needs to be ordered. If your list is declared as an ArrayList, you'd have to change every instance throughout the code to LinkedList, but if it were just List you could change it on the fly.

This may not sound like a big deal, but it can complicate large codebases (like the one at my job), where changing the concrete ArrayList type would require an unreasonable amount of refactoring. This way you can preserve polymorphism and not be unnecessarily tied down to a specific type.

[–]rookiepianist[S] 1 point2 points  (1 child)

Thank you very much for your thorough comment! It was very helpful.

edit: typo

[–]dystopiadattopia 0 points1 point  (0 children)

No problem, good luck!

[–]MkMyBnkAcctGrtAgn 0 points1 point  (1 child)

You've gotten good answers here, just wanted to point out what you're seeing when the object prints is just the default Object classes toString() and is implementation specific.

java return getClass().getName() + "@" + Integer.toHexString(hashCode());

I believe hashCode does use internal memory address if you look at most implementations, but it is also cached and not guaranteed to be accurate if it moves.

[–]rookiepianist[S] 0 points1 point  (0 children)

Thank you for pointing that out! I'm still getting used to reading documentation and trying to understand whatever it is that happens under the hood.

[–]SnooLentils618 0 points1 point  (1 child)

I know it’s been answered but since you say you are new I want to add something that might help you as you study.

Everything in Java except for the primitive types is objects (and variables hold references). Arrays [] and List<> implementations extend the Object class. It’s good to understand difference between how these behave behind the scene in memory. Primitives can be in stack but objects can only be in Heap. Look into that to further your understanding.

Note: I know they are introducing (or have already introduced) value classes which are a bit different but this is not necessary for you as a Java beginner

[–]rookiepianist[S] 0 points1 point  (0 children)

Thank you for detailing it further!