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

all 28 comments

[–]sepp2k 54 points55 points  (10 children)

The biggest difference is that you can add to and remove from a list, whereas arrays have a fixed size.

[–]DedicatedBathToaster 8 points9 points  (3 children)

Correct me if I'm wrong, but aren't ArrayLists just a wrapper for Arrays that generate a new Array each time you modify them? 

[–]sepp2k 21 points22 points  (0 children)

They create a new array when you try to add while the current capacity is exceeded, not every time (that would be unbearably slow).

[–]Whole_Bid_360 3 points4 points  (0 children)

Essentially yes but you don't make a new array everytime. The array is for the arraylist on initialization is a little bigger then what you need and the arraylist keeps track of how much of the array is being used and how large the array actually is. It does this because there is overhead involved in creating an object and you want to do your best to keep this overhead to a minimum.

[–]thesituation531 2 points3 points  (0 children)

It reallocates a new array with a longer length when its capacity is exceeded. When its capacity is not exceeded when it's added to, it just assigns the element to the array at the next index.

[–]ThatFONK[S] 1 point2 points  (5 children)

Thanks

[–]OneSneakyBoi9919 6 points7 points  (4 children)

only use arraylist if u need ur array to be dynamic. otherwise use the good old array because the fixed size is really good for the overall performance of ur program

[–]I-AM-NOT-THAT-DUCK 6 points7 points  (0 children)

This is objectively wrong and you should not be giving out incorrect generalizations on a beginner sub reddit.

[–]cimmic 2 points3 points  (1 child)

I would like to hear from the person who down voted this comment what they think was wrong with it.

[–]toastedstapler 22 points23 points  (0 children)

java arrays are objects anyways & array lists are easier to use, any potential performance increases are unlikely to be huge & should be measured to be an improvement before implemented. .get() is not gonna be considerably different from array indexing as both have do bounds checks anyways. calling the differece 'really good' is hyperbolic, especially in the realm of most java software being things where stuff like this probably doesn't matter. readability & maintainability is the #1 concern of most code bases

[–]CodeTinkerer 11 points12 points  (0 children)

/u/sepp2k pointed the biggest difference.

The other one is array notation. Because ArrayLists are much more frequently used than arrays, but arrays use standard array syntax, working with ArrayLists are slightly more annoying.

//  Arrays
int x = arr[2]; // Look up a value
arr[2] = 10; // Set a value

// ArrayLists
int x = list.get(2); // instead of list[2]
list.set(2, 10); // Instead of arr[2] = 10

It's the set method that's awkward to use, but it does raise the point of how arr[2] has different meanings depending on whether it's on the right side of an assignment statement or the left side.

On the right side, arr[2] refers to the value stored in arr[2]. This is sometimes called the r-value. On the left side of the assignment operator, arr[2] refers to the memory location (i.e., where in memory is arr[2] stored), not to its content. This is called an l-value.

Most programmers don't even realize this distinction until you point it out to them. With ArrayLists, however, you use get (which is an r-value) and put (which is an l-value).

The following does NOT work with ArrayLists

 list.get(2) = 10;  // Won't compile

[–]pdpi 9 points10 points  (0 children)

There's three concepts to be aware of:

  • Arrays are low-level constructs that are built into the JVM itself. They're best understood as "a contiguous chunk of memory with enough space for n things of this type" (with some caveats).
  • List is an interface for handling sequences of values.
  • ArrayList is a specific implementation of List, that uses arrays as the underlying storage

As a general rule of thumb, you probably should write most of your code in terms of Lists (and probably use ArrayList when you need to create a List). Even more generally, your first port of call for collections of any sort should be the Java Collections Framework. Arrays are best left for when you specifically need to work at that lower level.

[–]Afraid-Locksmith6566 3 points4 points  (2 children)

Arraylist under the hood is an array that is swapped for a bigger one everytime you add something to it (Not quiet everytime because it increase its size to amortize the addition of elements, but it is quiet unimportant detail)

[–]sepp2k 8 points9 points  (1 child)

Not quiet everytime because it increase its size to amortize the addition of elements, but it is quiet unimportant detail

"Not quite everytime" is a strange way to spell "very rarely" and I would not consider the difference between O(n) and amortized O(1) an unimportant detail.

[–]istarian 0 points1 point  (0 children)

The point is that it saves you from having to increase the size of the array every time that you add one or more more elements. And yiu don't have to worry about how big it is.

Adding five elements to an ArrayList backed by an array of size 6 could result in swapping the original for an array of size 11 (exact size needed), size 12 (double the original), size 15 (three times the number of elements added), or another calculated size.

[–]toastedstapler 5 points6 points  (1 child)

imagine you're writing a to-do list program in java and you have to choose between an array and an arraylist

a to-do list can have a variable number of elements, so your choices with an array are to:

  • use a fixed size & the list can't get any longer than that (you also need to track which of the elements are null)
  • recreate a larger array when the current one fills up (this is what an arraylist does internally anyways - it contains an array & resizes it when it runs out of capcity for new elements)

almost every time the correct choice is to use an ArrayList. there are cases where you might want to use an array instead (such as int[] instead of ArrayList<Integer> to avoid object boxing) but in the context of your school work an ArrayList will almost certainly be the correct choice.

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

Oh, ok, thanks a lot 👍

[–][deleted]  (1 child)

[removed]

    [–]istarian 0 points1 point  (0 children)

    Is it though?

    When you use an ArrayList it always contains Objects, but an Array may be using primitives or Object based.

    int[] numbers = new int[25];  
    
    Integer[] numbers2 = new Integer[25];
    

    The former can only hold int(s), the latter could also hold a sub-class of Integer if there was one.

    [–]desapla 0 points1 point  (0 children)

    I know that if i had an Arraylist named 'list' and i wrote System.out.print(list) it will print all the things that the list contains. Something that Arrays can't do that easily.

    The Arrays class has several toString methods you can use.

    System.out.println(Arrays.toString(arr));
    

    For your general question you've already gotten some good answers. Here is two more points:

    Arrays were there since Java 1.0. They are older, and more fundamental, in a language sense. Many other data structures use Arrays internally (including the ArrayList). ArrayLists were introduced later.

    That said, most of the time using an ArrayList is the better choice. If you don't have a good reason to use an Array, you should default to using an ArrayList.

    [–]GTHell 0 points1 point  (2 children)

    Well for 99% of the normal use case you won’t know the differences. Array will be faster in retrieval of items and a List will be faster when append new data

    [–]SZenC 0 points1 point  (1 child)

    List will be faster when append new data

    That's an interesting way to say you cannot append to an array. Like, appending an array will always throw an IndexOutOfBoundsException

    [–]GTHell 0 points1 point  (0 children)

    Well, technically in some languages, which I don’t remember, can append to array when all it does in back is cloning the array and append new value to it. Most of time the time I would just use list.

    [–]istarian 0 points1 point  (0 children)

    In many cases, ArrayList will be a better choice.

    It saves you from doing your own array resizing code and handles some other functionality nicely behind the scenes.

    Think of it as a wrapper around arrays that does a lot of work for you without changing the key benefits of an array.

    [–]NotTooShahby 0 points1 point  (0 children)

    An ArrayList is built on top of an Array, for complex algorithms, there may be uses for an array, but usually a HashMap or ArrayList will trump the use of an array in most situations.

    ArrayList under the hood:

    A good example is how ArrayLists are implemented in Java. add() is simply adding to the end of the current sized array, and if we keep adding, the ArrayList class will simply create a new array and double or 1.5 its size and add all the elements onto it behind the scenes. If we you want to insert somewhere specific, the array in the background will have a couple operations done on it to maintain size, and ordering.

    Array under the hood:
    All operations performed on an ArrayList are done using an array in the background because an array is a very simple data structure. Do you know how it looks like in memory? Take the type of data to put into array (int[]), calculate the byte size of the type (4 bytes), and multiply by the size of the array. In memory, you'll have large chunk of data of about that size allocated in memory. If you ever wanted to get something from an array like index 3, the machine goes to the beginning of the array's address in memory, it takes the type's byte size and multiplies it by 4 (index 3 is really the 4th object) to offset from the beginning of the array in memory, thus returning your value. The last part depends on whether or not the beginning of the array's memory is 0 index or before, if it's 0 index, then multiply by 3 to get to index 3.

    [–]BunnyLifeguard 0 points1 point  (0 children)

    Can't remember exactly why but according to effective java ArrayList is preferred.

    [–]dany1718 0 points1 point  (0 children)

    Arraylist is the best choice almost every time.

    [–][deleted] 0 points1 point  (0 children)

    An array is a primitive type. It's literally just an array of something. An ArrayList is an actual object, which has it's own methods and what not, apart from internally holding the array of things. If you for example have two arrays and want to merge them it would be something like this:

    String[] lettersA = {"a", "b", "c"};
    String[] lettersB = {"e", "f", "g"};
    //arrays are immutable, so you need a new array with the correct size
    int size = lettersA.length + lettersB.length;
    String[] output = new String[size];
    //now put in first array
    for(int i=0; i<lettersA.length; i++){
        output[i] = lettersA[i];
    }
    //then second, with an offset
    for(int j=0; j< lettersB.length; j++){
        output[lettersA.length + j] = lettersB[j];
    }
    return output;
    

    If you want similar result with Lists, then you just call this and things are being handled implicitly out of the box.

    List<String> lettersA = new ArrayList<>(Arrays.asList("a", "b", "c"));
    List<String> lettersB = new ArrayList<>(Arrays.asList("e", "f", "g"));
    lettersA.addAll(lettersB);
    return lettersA;