Learning Programming #1.6 The Basics: Lists

Lists are a way of storing variables. Lists can behave similar to an array, but can vary in size.
In my last posts you learned about arrays which are a foundation to the most common lists.

Lists are themselves objects and the values can be accessed with functions like:
get(int index); // Returns the object at the position index.

set(Object x, int index); // Sets the object at the position index to be that object.

add(Object x); // Puts this object at the end of the list.

remove(Object x); // Remove this object out of the list and close the thereby created gap between the two neighbouring objects`
remove(int index); // Remove the object at the position index out of the list and close the thereby created gap between the two neighbouring objects

Some languages also allow you to put objects in between two other objects, but that behaviour is usually not necessary and slow.

The most common list type stores an array of a certain length with some positions at the end of the array being empty. The number of positions filled is stored in a variable. If the all positions are filled then the list is resized by creating a new array and copying all elements to fit the new variable. If there are less than a certain number of variables in the array, the list is also resized to free memory.
To fill the gap when an element is removed it is necessary to copy a lot of the elements of the array.
An example implementation is shown below:
Screenshot from 2019-05-10 14-26-43.png

Task

You might have noticed that I didn't implement all functionality I described above. That will be your task.

In python you can use lists instead of arrays and again you need no type declaration so it isn't too much syntax.
Using lists in java is a bit more Complex since you need to tell the List what types it should store:
ArrayList<Object> list = new ArrayList<Object>(startingCapacity);
You can use the functionality I told you about above on that list.
There is only one problem about the java Lists: You cannot store primitives. There is a way to store primitives in the java standard library lists, but I suggest you should make your own implementation of lists like I showed above, because storing primitives in java standard library lists is slow and eats memory.

This is the end of the The Basics. I hope you understood everything. If you didn't, don't hesitate to ask me.
In the next chapter(#2) I will show you how to make some more advanced stuff like creating a window and paint some nice graphics in java.

H2
H3
H4
Upload from PC
Video gallery
3 columns
2 columns
1 column
5 Comments