Skip to content Skip to sidebar Skip to footer

Java Equivalent Of Python List

In Python there is a data structure called 'List'. By using 'List' data structure in Python we can append, extend, insert, remove, pop, index, count, sort, reverse. Is there any si

Solution 1:

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.

Solution 2:

Java has an interface called list, which has implementations such as ArrayList, AbstractList, AttributeList, etc.

https://docs.oracle.com/javase/8/docs/api/java/util/List.html

However, each one has different functionalities, and I don't know if they have everything you've specified such as .reverse().

Solution 3:

Take a look at Collections in java. There are many lists (ArrayList, LinkedList etc). Choose the best datastructure needed for the requirement and complexity (both space and time).

Post a Comment for "Java Equivalent Of Python List"