Java equivalent of Python List

The closest Java has to a Python List is the ArrayList<> and can be declared as such

//Declaring an ArrayList
ArrayList<String> stringArrayList = new ArrayList<String>();

//add to the end of the list
stringArrayList.add("foo");

//add to the beggining of the list
stringArrayList.add(0, "food");

//remove an element at a spesific index
stringArrayList.remove(4);

//get the size of the list
stringArrayList.size();

//clear the whole list
stringArrayList.clear();

//copy to a new ArrayList
ArrayList<String> myNewArrayList = new ArrayList<>(oldArrayList);

//to reverse
Collections.reverse(stringArrayList);

//something that could work as "pop" could be
stringArrayList.remove(stringArrayList.size() - 1);

Java offers a great selection of Collections, you can have a look at a tutorial that Oracle has on their site here https://docs.oracle.com/javase/tutorial/collections/

IMPORTANT: Unlike in Python, in Java you must declare the data type that your list will be using when you instatiate it.


Several collections exist, but your probably looking for ArrayList

In Python you can simply declare a list like so:

myList = []

and begin using it.

In Java, it better to declare from the interface first so:

List<String> myList = new ArrayList<String>();

Python          Java
append          add
Remove          remove
len(listname)   list.size

Sorting a List can require a little more work, for example, depending on the objects you may need to implement Compactor or Comparable.

ArrayList will grow as you add items, no need to extend it on your own.

As for reverse() and pop(), I'll refer you can refer to:

How to reverse a list in Java?

How to pop items from a collection in Java?

Tags:

Python

Java