14

I'm fairly out of touch with my Java programming and am doing Google's Udacity course as a refresher. I was going through lesson 1 on the Sunshine app where the lecturer chose to create fake data by declaring an array of strings and then converting it to an ArrayList.

The code is the following:

String[] data = {
            "Mon 6/23 - Sunny - 31/17",
            "Tue 6/24 - Foggy - 21/8",
            "Wed 6/25 - Cloudy - 22/17",
            "Thurs 6/26 - Rainy - 18/11",
            "Fri 6/27 - Foggy - 21/10",
            "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
            "Sun 6/29 - Sunny - 20/7"
    };
    List<String> weatherForecast = new ArrayList<>(Arrays.asList(data));

I was wondering is there any advantage to using this convertion method? Why not just immediately declare the data as an ArrayList as such:

    ArrayList weatherForecast = new ArrayList();
    weatherForecast.add("Today - Sunny - 88/63");
    weatherForecast.add("Tomorrow - Foggy = 70/46");
    weatherForecast.add("Weds - Cloudy - 72/63");
    weatherForecast.add("Thurs 6/26 - Rainy - 18/11");
    weatherForecast.add("Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18");
    weatherForecast.add("Sun 6/29 - Sunny - 20/7");

Thanks!

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
Patryk
  • 279
  • 1
  • 10
  • Maybe the lecturer just wanted to demonstrate that you can convert between arrays and Lists readily using the Collections API. ArrayList uses an array under the covers. In some circumstances (but not this one) you may squeeze a small performance advantage out of using an array, but Lists will provide a great deal more functionality. So no great difference, depends on what you intend to do with it. You might like working with an array rather than a List - until you need some of the functionality that a List will provide over an array that is. – jacks Aug 19 '15 at 10:33
  • Aggregate array declarations such as this are done to instantiate an array of static data whereas Lists imply a dynamic form and also a far more likely parameter to a method call than an array. Converting from one to the other is like saying "Now it's constant, but we expect to be given a List in future development." At least this is how I read it. Adding the data directly to an ArrayList is the equivalent of putting `! important tags` next to rules in css files. In other words, a little crude, even if it works. ;) – Neil Aug 19 '15 at 14:18

5 Answers5

12

The "normal" way would be to use a third form:

List<String> weatherForecast = new ArrayList<>();
Collections.addAll(weatherForecast,
        "Mon 6/23 - Sunny - 31/17",
        "Tue 6/24 - Foggy - 21/8",
        "Wed 6/25 - Cloudy - 22/17",
        "Thurs 6/26 - Rainy - 18/11",
        "Fri 6/27 - Foggy - 21/10",
        "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
        "Sun 6/29 - Sunny - 20/7");

List is an interface, using that will enable to use another implementaton class like LinkedList (for just a couple of elements). Also useful as parameter type.

This uses the Collections utility class to add varargs ... strings. And uses under the hood a String[] for those args.

The .asList of the first option would be sufficient to have a List<String> not to be added to.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • @sᴜʀᴇsʜᴀᴛᴛᴀ both styles can be found in old style code, the first a bit more recent, but more circumstantial. The second most direct, but too verbose. – Joop Eggen Aug 19 '15 at 10:39
  • There is nothing wrong with this way, but I personally prefer the conversion from an array in OP's first example. – Neil Aug 19 '15 at 14:23
5

Both do the same thing.

But the difference is that the first makes it more readable. You would exactly know that you're adding weatherforecast information to a list.

In the second case you just keep on adding information, using add(), this actually looks a bit clumsy than the other.

Consider you are adding prime numbers to a list

First Approach:
int [] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
List<Integer> primes = new ArrayList<>(Arrays.asList(primeNums));

Second Approach:
List<Integer> primes = new ArrayList<>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
primes.add(11);
primes.add(13);
primes.add(17);
primes.add(19);

Also you could iterate through the array and add it.

for(int i = 0; i < primeNums.length; ++i)
  primes.add(primeNums[i]);
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
5

First approach :

  • Better readability (can be even better, see my alternative); all datas are separated directly by comma instead of having a method call to add each one.
  • Arrays.asList Create a fixed-size list for the given specific array using it internal ArrayList class which is just a wrapper around the array itself that make it more efficient then creating a full copy of the array.
  • You keep the data in a List variable instead of an ArrayList variable which gives you more flexibility.

Second approach :

  • You are using raw types, it's bad at the beginning.
  • No advantages.

Please if you use that approach, at least declare your List in a generic manner :

ArrayList<String> weatherForecast = new ArrayList<>();

Alternative :

Note that you could directly do :

List<String> weatherForecast = Arrays.asList(
    "Mon 6/23 - Sunny - 31/17",
    "Tue 6/24 - Foggy - 21/8",
    "Wed 6/25 - Cloudy - 22/17",
    "Thurs 6/26 - Rainy - 18/11",
    "Fri 6/27 - Foggy - 21/10",
    "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
    "Sun 6/29 - Sunny - 20/7"
);
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • You specified first and at the end, you used it as a alternative. I'm confused :) – Suresh Atta Aug 19 '15 at 12:02
  • @sᴜʀᴇsʜᴀᴛᴛᴀ I specified it, but never qualified it as a pros/cons; it just need to be used as it is meant to. I assume that if the lecturer use it then there is no problem with the fact that it is immutable. Considering this, I've given an alternative that does the same in a more readable way. – Jean-François Savard Aug 19 '15 at 12:04
2

Both are doing same thing; but code readability matters;

Consider an example--

An application is allowed to put values into arrays upto maximum capacity and as per this link, maximum of Integer.MAX_VALUE - 5 values can be allowed in array. Once array got populated, developer needs to convert it into List as you are doing above.

Now, think if some one is using add method in this situation then definatly lines of code will grow and code will become difficult to read.

So in this situation, preferred operation would be using Arrays.asList(data);

Community
  • 1
  • 1
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36
1

There is no special advantage.

In your first case you are needlessly wrapping the array created by Arrays.asList() as a new array.

Use the second case, provided the array content is static.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I would say that the "advantage" is that you have to write less code using the first approach... If it can be called "advantage" – BackSlash Aug 19 '15 at 10:29
  • @BackSlash Seems no advantages for me in this case :) – Suresh Atta Aug 19 '15 at 10:44
  • Actually Arrays.asList returns a list with read only structure.. you cannot add or remove from the list. . Also, Arrays.asList doesn't return java.util.arraylist. it returns java.util.arrays$arraylist. This is important Coz instanceof checks could fail – TheLostMind Aug 19 '15 at 12:02
  • @TheLostMind: So? Unless the variable is actually declared as ArrayList, one should not assume it has the possibilities of an ArrayList. This is exactly why I despise declaring variables as supertypes instead of the actually used type. – Nyerguds Aug 19 '15 at 21:52
  • 1
    @Nyerguds - I agree *coding to the interface* is preferred 99% of the time.. But there could be situations where you would explicitly be expecting on type of list over another for performance reasons. – TheLostMind Aug 20 '15 at 07:13
  • 1
    @TheLostMind As I said, I really dislike 'coding to the interface', since most of the time, all that does is unnecessarily hiding the specific options of the actually used implementation. That was actually more a snide comment against the declaration of the variable as `List` than against the calling of the `ArrayList` constructor. – Nyerguds Aug 21 '15 at 08:28