JM Safe

From Zemana
Hello guys,

as I said I will talk about ArrayList in Java. ArrayList are a more sophisticated structure than arrays, but they are a bit different than the arrays. When you initialize an ArrayList variable you don't have to specify the length of the ArrayList, it is a flexible data structure. Here is some examples of using ArrayList:

ArrayList<String> exampleArrayList =new ArrayList<String>(); //there we create our arraylist, and the type is "String", so our arraylist will contain only "String" elements.
exampleArrayList.add("M"); //there we add the element to our arraylist
exampleArrayList.add("T"); //there we add the second element of our arraylist

//to remove an element is pretty similar and easy:


//use this if you want to remove ALL elements from the arraylist:


//it is easy also to get an element present at a certain position in the list:

String firstElement = exampleArrayList.get(0); //there we get the first element of the list (index 0)

//here is instead a method to verify an arraylist is empty (it doesn't contain elements) or not:

boolean empty = exampleArrayList.isEmpty(); //we save the output of this method in a boolean variable (true or false)

//if we want to know if a certain element is contained in an arraylist we can write that:

    System.out.println("yes, it contains M");

//there, instead, we will loop through our ArrayList:

Iterator iteratorList = exampleArrayList.iterator(); 

while(iteratorList.hasNext()) {  //we verify if we reached the end of our ArrayList or there are others elements to write

System.out.println(;  //let's write ArrayList elements


//if you want to get the index (position) of a certain element contained in the arraylist you can do that:

int positionOfElement = exampleArrayList.indexOf("M"); //it should return 0 because "M" is the first element of the arraylist.

//the last method I want to describe in this thread is "size()", which let us to know the size of our arraylist:

int lengthList = exampleArrayList.size();
ArrayList structures are faster (in terms of execution and performance) than arrays. So... what is the best? Arrays or ArrayLists? It depends on the project you want to develop; surely arrays can be useful if you want a fixed length of your list, but if you need for example a fast, and dynamic, flexible list I would go for ArrayLists.
If you want to know more about ArrayLists in Java and discover other useful and powerful methods you can click here: ArrayList (Java Platform SE 8 )

Thank you all! ;)
Last edited: