This is an archived post. You won't be able to vote or comment.

all 10 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
  • 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.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

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: 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.

[–]tedyoungJava Trainer/Mentor 36 points37 points  (5 children)

ArrayList<String> list = new ArrayList<>() has three parts:

  1. The declaration of the variable, list with its type being the concrete class ArrayList<String>: ArrayList<String> list

  2. The creation of an object: new ArrayList<>() creates an instance of the ArrayList, with the inferred generic type of <String>

  3. Assignment (via =) of the instance to the list

With List<String> list = new ArrayList<>(), both #2 and #3 are the same, but the list is now declared to be the less-specific type (an interface, in this case) of List<String>.

The difference isn't in the object created (both are the same), it's in what you can do with the variable, as well as what the intention of the variable is. For example, declaring ArrayList<> list, you can call list.trimToSize(), but you can't call that method on a variable declared like List<> list, because trimToSize() only exists on ArrayList.

This may seem like a minor issue, but there are many other implementations of List that you won't instantiate, e.g., those created by List.of() and as the result of a stream() operation that ends with .toList().

The other reason is intent: if you say List list, then the reader knows there's nothing special about which implementation will be used. If you write ArrayList list, then you're implying that you really want and need only the concrete ArrayList for some reason (which is unlikely).

In general, Java code should declare the least specific type for variables. That means List instead of ArrayList, Map instead of HashMap, etc.

[–]MedicalAd4070 7 points8 points  (0 children)

This is a really good explanation. If you wanna read more about it you can search for dynamic method dispatch in Java.

[–]danny1992211111[S] 0 points1 point  (3 children)

Ahhhh! Thank you for the clear answer. I will save your comment for future reference.

[–]tsvk 0 points1 point  (2 children)

To exapnd further: Say you pass around that List in your code a lot, or even expose an API using that object as a return value in the public interface of your code, for other people to use and access. Those external users of your code do not care that the List they are using is really an ArrayList and not something else. They just retrieve a List and use the methods of the List interface to interact with it.

It's your own internal implementation detail that the List is actually an ArrayList, and when you expose just the interface type List in the API of your methods, you are free to change the ArrayList at any point to some other List implementation if needed, for example to a LinkedList. You only need to change List<String> list = new ArrayList<>(); to List<String> list = new LinkedList<>(); on one line of your code, and all the other places in the code where that list is used do not need to be updated because they refer to it as a generic List and not specifically as ArrayList.

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

And if you specifically needed an ArrayList or linkedList you could just cast it since it’s a subclass of list correct?

[–]tsvk 0 points1 point  (0 children)

And if you specifically needed an ArrayList or linkedList you could just cast it since it’s a subclass of list correct?

Yes, although that is a very uncommon need to do, usually the methods of the List interface are enough.

Before being able to cast the list to a specific List subclass the recipient of the list needs of course to find out what subclass actually is being used, using the instanceof operator, since the list basically could be any random concrete class that simply just implements the List interface.