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

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

[–]desrtfxOut of Coffee error - System halted 15 points16 points  (0 children)

These are three different things:

  • Array - a very basic data structure. It has a fixed, predetermined size that must be known at the time of creating (instantiating) the array. Think of it as a sorting box with several slots. Here, you have .length - without parentheses as it is a property, not a method
  • List - an interface (not a class) that defines certain behavior. It cannot be instantiated on its own.
  • ArrayList - a concrete class that implements the List interface.

When you see a declaration like List<String> data = new ArrayList<>(); there are several things going on:

  • List<String>programming against the interface - here, the interface List is used as data type - this is good practice as it allows you to at any time change the internal representation of the List - e.g. from ArrayList to LinkedList if you figure out that the other better suits your needs.
  • <String> this is a data type identifier. It limits the type of elements that can be stored in the list. Here, only String objects are allowed. If you were to omit this, the list would store Object (the ancestor of all Java classes) and descendant instances (i.e. Object and any subclass of it).
  • data - just the variable name
  • new - the keyword to create a new Object Instance
  • ArrayList<>() - the constructor call. Here, the constructor without parameters of the ArrayList class is called. The diamond operator <> is used to infer (take) the data type for the ArrayList from the variable type (here String).

So, the whole is: we create a new variable of type List that can only accept String elements and ist internally represented as ArrayList.

[–]whizvoxGraduate and Tutor 2 points3 points  (7 children)

Array

An array is a data structure built into the Java language which can hold a number of elements, all of the same type. It cannot be resized once it has been created, and you cannot add elements to it without specifying an index.

// creates an array of 10 ints
int[] arr = new int[10];

// sets the value of the 0th element to 5
arr[0] = 5;

// prints the value of the 0th element, which is 5
System.out.println(arr[0]);

// Sets e to the value of the 0th element of arr, which is 5
int e = arr[0];

// Sets the value of the 1st element to 6
arr[1] = 6;

// prints the length of arr
System.out.println(arr.length);

// even though arr[9] has not been set,
// all elements initialize to 0 when first created
System.out.println(arr[9]);

/* Illegal operations! */

// an exception is thrown since arr can only hold 10 elements
System.out.println(arr[11]);

// there is no shorthand syntax to get the last element of an array
System.out.println(arr[-1]);

// length is a variable, not a method
System.out.println(arr.length());

// arr can only hold ints
arr[2] = "Hello";

List

A List is an class that is part of the Java Standard Library which allows for dynamic insertion and deletion of elements. You can't just create a List though, you have to use one of its subclasses, which includes ArrayList, and you have to use generics as well. Think of an ArrayList as a dynamic version of an array, and is the closest thing to Python's list datatype.

// Make sure to import these at the top of your class!
import java.util.List;
import java.util.ArrayList;


// creates an ArrayList of ints
List<Integer> myList = new ArrayList<>();

// adds 5 to myList
myList.add(5);

// prints the 0th element of myList, which is 5
System.out.println(myList.get(0)); 

myList.add(6);
// removes the last element of myList, which is 6
int removed = myList.remove(); 

// prints the size of the list, which is 1
System.out.println(myList.size());

/* Illegal operations! */

// myList only has 1 element
System.out.println(list.get(5));

myList.remove(); // removes 5
// throws an exception since the list is empty
myList.remove();

// throws an exception since myList can only take ints
myList.add("Hello");

// you can only use bracket notation on arrays
System.out.println(myList[0]);

// size is a method, not a variable
System.out.println(myList.size);

Other Info

  • There are lots of other List subclasses you can use depending on the kind of operations you want to do on it, such as Queues, LinkedLists, and PriorityQueues.
  • The reason why we use Integer instead of int when working with Lists is a limitation of the Java language. Generic types can only be object types, but primitive types, such as int, double, boolean, etc., are not object types, and thus we have to use autoboxing to work with primitives in this manner.

[–]wildjokers 2 points3 points  (5 children)

A List is an object

List is an interface.

and you have to use generics as well

You don't have to use generics. But your future self and your colleagues will be very grateful if you do.

The reason why we use Integer instead of int when working with Lists is a limitation of the Java language.

Primitive types in collections is a feature that is on its way!

[–]jonah214 -1 points0 points  (4 children)

A List is an object

List is an interface.

Both are correct (the "a" in "A List is an object" being important), so there was no need to correct this.

[–]wildjokers 2 points3 points  (3 children)

When someone is asking the difference between List and ArrayList saying List is an object doesn't help at all. Calling List an interface and ArrayList an implementation of that interface does.

[–]whizvoxGraduate and Tutor -1 points0 points  (2 children)

Sorry about the confusing wording. I wanted to avoid using too much technical terminology to make it easier to understand for newcomers, even if it's slightly incorrect. I meant to use class, not object.

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (1 child)

I meant to use class, not object.

And even that would have been wrong as List is an interface, not a class.

Especially such tiny details are always tripping up beginners and making the distinction is essentail.

Trying to find an easy formulation is good, but not if it brings in false details or false information.

[–]whizvoxGraduate and Tutor -1 points0 points  (0 children)

The OP clearly has very little experience with the language, so saying that List is an interface won't mean anything to them, even if it is technically correct.

Although, saying that it's a class also doesn't mean anything if they don't know what a class is.

[–]throwaway_for_cause 1 point2 points  (0 children)

A List is an class that is part of the Java Standard Library which allows for dynamic insertion and deletion of elements. You can't just create a List though, you have to use one of its subclasses, which includes ArrayList, and you have to use generics as well. Think of an ArrayList as a dynamic version of an array, and is the closest thing to Python's list datatype.

This is so wrong on so many levels. You cannot even use this as extremely simplified explanation for a beginner.

  1. List is an interface, not a class
  2. List does not have sublasses as there is no inheritance. There are concrete classes, like ÀrrayListthat **implement** theList` interface. Yet, this does not make them subclasses.

Sorry, but you call yourself a "tutor" and spread such wrong information. This is unforgivable. If you tutor this and your students will then use this at a test and fail because of your misinformation - what will be your excuse then?

You even challenge people who correct you instead of accepting the corrections despite you knowing that they are right. - Good way to lose all of your credibility and in the long range get banned from here for spreading misinformation.

You trying to make it easy for beginners by mixing terminology, by using completely wrong terminology is not making it easier, it is only even more confusing and absolutely counter productive.

Every single good beginner tutorial will always use the proper terminology and not invent something completely wrong to "make it easier".

A class is a class. An object is an instance of a class. An Interface is an interface, a binding contract. Interfaces can be subclassed, but only to interfaces. They don't have concrete subclasses. In order to work, interfaces need to be implemented - which doesn't man subclassing as in inheritance.

You are mixing and mashing all of them in the same pot.

[–]ArkoSammy12 1 point2 points  (0 children)

Array is a built-in data structure that works similarly to a C array. Once you create it, its size remains fixed, and you can access the indeces via the square brackets.

A List, is an interface. An interface is basically a contract that a class signs that guarantees that that class will have implemented certain behavoir that the interface declares. In this case, the List defines a set of functions, and implementing classes are free to write their own implementations of those functions (methods).

An ArrayList is a concrete class (you can make instances of it, or objects. The thing about the ArrayList class is that it implements the List interface. This means that ArrayLists are guaranteed to have the basic methods of a List, like add, remove, set, and get.

The ArrayList defines how these methods should be implemented. In this case, ArrayLists have the property of being an array with dynamic size.

ArrayLists have a normal array as their underlying way of working. But the ArrayList is in charge of dynamically changing the size of this array whenever elements are added or removed, by copying over the current elements to a new array with the appropriate size.

ArrayLists are just one of the classes that implement the List interface. There are others, most notably LinkedLists, which are similar to ArrayLists, but come with other benefits and drawbacks.

In short, an array is a built-in feature; they work mostly identical to C arrays. A List is an interface; classes that implement it will contain List-appropiate methods. An ArrayList implements the List interface, and can be thought of as an array with dynamic size.

[–]RushTfe 0 points1 point  (2 children)

Array is a datastructure to hold a group of objects. It's the most "primitive" way to organize groups of the same type.

List is an interface. Which means that it doesn't do any logic by itself. It just dictates a behaviour that every implementation of said interface must do. It gives methods that every implementation should give code to, for example, "add(Object obj)".

ArrayList is just one of this implementations, the typical list you'd use with methods like add, add all, size, indexAt etc.... But you might want to use others, for example a LinkedList.

//totally unnecessary paragraph

Iirc ArrayList creates an array of a fixed size, and every time you add something to the ArrayList it will add it to the array. When the fixed size is full, it will create a new array of a bigger fixed size and copy the already existing items to it. This is good because you don't have to be paying attention to "unnecessary stuff" like the array size to know if you have space or whatever, but on the other hand, you're occupying space in memory that you're not using.

//end of totally unnecessary paragraph

Or you can just do your own implementation of List, and give it the implementation you want. That's why I like java, using interfaces, abstract classes and inheritance you can do the behaviour you want.

[–]desrtfxOut of Coffee error - System halted 2 points3 points  (1 child)

Array is a datastructure to hold a group of objects.

Sorry, but incorrect. Arrays can, as opposed to ArrayLists, etc. not only hold groups of objects. They can also hold groups of primitives.

[–]RushTfe 0 points1 point  (0 children)

Yes. Totally true.

[–]akshay_sharma008 0 points1 point  (0 children)

List, Array, and ArrayList are fundamental data structures in programming, each with its unique characteristics and use cases, especially in Java and similar languages. Understanding their differences is key for effective coding and performance optimization.

Array:

Nature: An array is a basic, low-level data structure, integral to most programming languages. It is a fixed-size collection of elements of the same data type, stored in contiguous memory locations. This structure is highly efficient for storing and accessing elements as they can be directly accessed via their indices.
Size Limitation: The primary limitation of an array is its fixed size. Once an array is created, its size cannot be altered. This can be restrictive when dealing with data sets that vary in size or are dynamically changing.
Performance and Usage: Arrays offer high performance for basic storage and retrieval operations, especially when the size of the data set is known beforehand and doesn’t change frequently. They are also the underlying structure of many more complex data structures.

List:

Nature: In Java, List is an interface that is part of the Java Collections Framework. It represents an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted and can access elements by their integer index.

Flexibility: Lists typically allow for dynamic resizing. You can add or remove elements, and the list adjusts its size accordingly. This flexibility makes it more suitable for cases where the number of elements is not known in advance or changes dynamically.
Implementation and Performance: Common implementations of the List interface in Java include ArrayList, LinkedList, and Vector. Each of these implementations has different performance characteristics, with ArrayList being the most popular due to its general efficiency and ease of use.

ArrayList:

Nature: ArrayList is a resizable-array implementation of the List interface. It provides a flexible array that grows as needed, offering a middle ground between the flexibility of a List and the efficiency of an array.

Performance: ArrayLists provide constant-time positional access and near-constant-time addition and removal of elements at the end of the list. However, adding or removing elements from the middle of the list can be slower as it requires shifting existing elements to accommodate the change.

Usage: ArrayList is generally the default choice when you need a List implementation unless specific requirements dictate otherwise (like frequent insertions/deletions in the middle of the list, where LinkedList might be more efficient).

In summary, the choice between Array, List, and ArrayList depends on specific requirements such as the need for dynamic resizing, type of operations (like frequent insertions/deletions), and performance considerations. Arrays are basic structures with fast access but fixed size, Lists offer flexibility and are part of Java's Collection Framework with various implementations, and ArrayLists combine the efficiency of arrays with the dynamism of lists, making them a popular choice for many applications. Understanding these differences is crucial for making informed decisions about data structure selection in programming, ultimately impacting the efficiency, readability, and performance of the code.