Java equivalent of Python List - java

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 similar data structure in Java where we can get all that function like 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?

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().

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

Related

How to shuffle/randomize elements within EnumSet in Java?

I have an EnumSet like this:
EnumSet<Fruit> otherFruits = EnumSet.complementOf(CURRENT_FRUIT);
I want to shuffle elements within otherFruits.
Is there any way to shuffle/randomize elements within this EnumSet? I don't want to convert it to List if possible. Can anyone provide an example as well.
I am using Java 7.
No, it's not possible to do this without conversion to another data type like array or list. Internally EnumSet does not preserve an order: it just stores a bitmask of used enum constants. This way it's much faster and takes very low amount of memory.
To solve your problem you can use ArrayList:
List<Fruit> fruits = new ArrayList<>(otherFruits);
Collections.shuffle(fruits);
Sets don't have a modifiable order. You'll need to convert this to a List or other collection type that does.

how to achieve this in java ? requirement given below

I want to create a list of list
List<integer> nodes[10]=new ArrayList();
i want this, coz i will be iterating through it and reading data..and it will be dynamically created in runtime depending upon the size of inputs
Creating an array of List seems a little weird to me, not that you can't do it, it just seems counter intuitive to me...
Instead, I'd create a List of Lists, something like...
List<List<Integer>> nodes = new ArrayList<List<Integer>>(10);
You would then just need to populate them with actually values, this will depend on what you are doing, but something like...
nodes.add(new ArrayList<Integer>(10));
When you need to access a particular list/node, you would just access it like any normal List
List<Integer> listOfIntegers = nodes.get(0);
Take a look at the Collections tutorial and List JavaDocs and ArrayList JavaDocs for more details.
An array of ArrayLists
List<Integer>[] nodes = new ArrayList[count];
An ArrayList of ArrayLists
List<List<Integer>> nodes = new ArrayList<List<Integer>>(count);

Which collection in java enables insterting between elements

I would like to use colllection(List like one) in java which enables inserting between to elements?
Collections that are derivative of List contain an add method that takes an index so you can do this. java.util.ArrayList is a common one...
Use add method of List
to specify the position where you want to insert in a list
Adding an element between elements is an optional operation, which by default in AbstractCollection is not implemented and throws a specific exception. Derived by AbstractCollection, AbstractList was added with out of the box implementation for add(int, E) so any concrete implementation of AbstractList will have it.
More important, choose an implementation that fit your needs of performance regarding memory consumption, reads, writes, etc...
The List interface has a function add(index,element) which adds an element at the specified index.
ArrayList<String> list=new ArrayList<String>();
list.add("Java") ;
list.add("JSP") ;
list.add("STRUTS") ;
list.add("EJB") ;
list.add(2,"C++");
The list interface declares a function add(int index, E element).
The ArrayList, LinkedList class has implementations for the above method. So can use either one of the above as per your requirement to add an element in between.
List os = new ArrayList();
os.add('Windows');
os.add('Linux');
os.add('Mac');
os.add(1,'Android')
Android will be added at the 1st index of the list i:e will be the 2nd element as index begins with 0.
You can use the add(int index, Integer element) function of the list.
In this function, you can specifically put the element in the range of list using the index value.
Here is the sample:
List<Integer> sampleList = new ArrayList<Integer>();
sampleList.add(1);
sampleList.add(2);
sampleList.add(3); //sampleList now contains {1,2,3}
Now if you want to put it between 1 and 2.
sampleList.add(1,4); //sampleList now contains {1,4,2,3}
We put the value 4 between 1 and 2.
Array List is the best way to Insert/Update/Delete like operations easily.
And also you can use Linked List for that but it is used mostly for large data.

Placing a List in the parameters of another List in java

Sorry if the title is unclear, but I wasn't exactly sure how to describe this in that little amount of words. Okay, so suppose we have this declaration:
ArrayList<String> list = new ArrayList<String>();
//add items to list
Set<String> set = new TreeSet<String>(list);
Now, from what I understand, set will receive the data from list and sort them because that's what TreeSets do. However, on the oracle website, I don't see any constructor in the HashSet class that takes a List as a parameter. So, I don't understand why this works if there is no defined constructor to accept a List as a parameter.
TreeSet has a constructor that takes a Collection, and List is a Collection (List extends Collection).
Many classes in the Java collections framework follow the same concept. ArrayList, for instance, also has a constructor that takes a Collection. This makes it easy to copy data between collections.
Take a look at TreeSet(Collection c). This accepts a Collection and ArrayList implements Collection.

How to initialize a dynamic array in java?

If I have a class that needs to return an array of strings of variable dimension (and that dimension could only be determined upon running some method of the class), how do I declare the dynamic array in my class' constructor?
If the question wasn't clear enough,
in php we could simply declare an array of strings as $my_string_array = array();
and add elements to it by $my_string_array[] = "New value";
What is the above code equivalent then in java?
You will want to look into the java.util package, specifically the ArrayList class. It has methods such as .add() .remove() .indexof() .contains() .toArray(), and more.
Plain java arrays (ie String[] strings) cannot be resized dynamically; when you're out of room but you still want to add elements to your array, you need to create a bigger one and copy the existing array into its first n positions.
Fortunately, there are java.util.List implementations that do this work for you. Both java.util.ArrayList and java.util.Vector are implemented using arrays.
But then, do you really care if the strings happen to be stored internally in an array, or do you just need a collection that will let you keep adding items without worrying about running out of room? If the latter, then you can pick any of the several general purpose List implementations out there. Most of the time the choices are:
ArrayList - basic array based implementation, not synchronized
Vector - synchronized, array based implementation
LinkedList - Doubly linked list implementation, faster for inserting items in the middle of a list
Do you expect your list to have duplicate items? If duplicate items should never exist for your use case, then you should prefer a java.util.Set. Sets are guaranteed to not contain duplicate items. A good general-purpose set implementation is java.util.HashSet.
Answer to follow-up question
To access strings using an index similar to $my_string_array["property"], you need to put them in a Map<String, String>, also in the java.util package. A good general-purpose map implementation is HashMap.
Once you've created your map,
Use map.put("key", "string") to add strings
Use map.get("key") to access a string by its key.
Note that java.util.Map cannot contain duplicate keys. If you call put consecutively with the same key, only the value set in the latest call will remain, the earlier ones will be lost. But I'd guess this is also the behavior for PHP associative arrays, so it shouldn't be a surprise.
Create a List instead.
List<String> l = new LinkedList<String>();
l.add("foo");
l.add("bar");
No dynamic array in java, length of array is fixed.
Similar structure is ArrayList, a real array is implemented underlying it.
See the name ArrayList :)

Categories