Showing posts with label Java list. Show all posts
Showing posts with label Java list. Show all posts

Monday, July 8, 2024

How ArrayList Works Internally in Java

ArrayList arguably would be the most used collection along with the HashMap. Many of us programmers whip up code everyday which contains atleast one of these data structures to hold objects. I have already discussed how HashMap works internally in Java, in this post I'll try to explain how ArrayList internally works in Java.

As most of us would already be knowing that ArrayList is a Resizable-array implementation of the List interface i.e. ArrayList grows dynamically as the elements are added to it. So let's try to get clear idea about the following points-

  • How ArrayList is internally implemented in Java.
  • What is the backing data structure for an ArrayList.
  • How it grows dynamically and ensures that there is always room to add elements.

Because of all these side questions it is also a very important Java Collections interview question.

Note that the code of ArrayList used here for reference is from Java 17


Where does ArrayList internally store elements

Basic data structure used by Java ArrayList to store objects is an array of Object class, which is defined as follows-

transient Object[] elementData;

I am sure many of you would be thinking why transient and how about serializing an ArrayList then?
ArrayList provides its own version of readObject and writeObject methods so no problem in serializing an ArrayList and that is the reason, I think, of making this Object array as transient.

Sunday, July 7, 2024

ArrayList in Java With Examples

Java ArrayList is one of the most used collection and most of its usefulness comes from the fact that it grows dynamically. Contrary to arrays you don't have to anticipate in advance how many elements you are going to store in the ArrayList. As and when elements are added ArrayList keeps growing, if required.

Though internally it is not really some "elastic" array which keeps growing, it is as simple as having an array with an initial capacity (default is array of length 10). When that limit is crossed another array is created which is 1.5 times the original array and the elements from the old array are copied to the new array.

Refer How does ArrayList work internally in Java to know more about how does ArrayList work internally in Java.


Hierarchy of the ArrayList

To know the hierarchy of java.util.ArrayList you need to know about 2 interfaces and 2 abstract classes.

  • Collection Interface- Collection interface is the core of the Collection Framework. It must be implemented by any class that defines a collection.
  • List interface- List interface extends Collection interface. Apart from extending all the methods of the Collection interface, List interface defines some methods of its own.
  • AbstractCollection- Abstract class which implements most of the methods of the Collection interface.
  • AbstractList- Abstract class which extends AbstractCollection and implements most of the List interface.

ArrayList extends AbstractList and implements List interface too. Apart from List interface, ArrayList also implements RandomAccess, Cloneable, java.io.Serializable interfaces.

Friday, February 16, 2024

Difference Between ArrayList And Vector in Java

In many ways Vector class in Java is just like ArrayList apart from some differences and this post is about those differences between the ArrayList and Vector in Java.

There are many similarities between Vector and ArrayList classes in Java. Vector, just like ArrayList, is also a growable dynamic array. As of Java v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework.

With JDK 5 it was also retrofitted for generics and implements Iterable interface too which means it can also use enhanced for loop.

ArrayList Vs Vector in Java

  • ArrayList is not synchronized whereas Vector is Synchronized. Which means that the methods in the Vector class are Synchronized making Vector thread-safe and ready to use as-is in a multi-threaded environment.
    ArrayList, if needed in a multi-threaded environment, has to be synchronized externally using Collections.synchronizedList method which returns a synchronized (thread-safe) list backed by the specified list.
  • Refer How and why to synchronize ArrayList in Java to know how to synchronize an ArrayList.

  • A Vector, by default, doubles the size of its array when it needs to expand the array, while the ArrayList increases its array size by 50 percent.
  • As mentioned though Vector is retrofitted to implement the List interface it still has legacy methods which are not there in ArrayList. As Example methods like addElement(), removeElement(), capacity() which are there in Vector class but not in ArrayList.
  • Performance wise Vector is comparatively slower than the ArrayList because it is synchronized. That means only one thread can access method of Vector at the time and there is an overhead of acquiring lock on the object too.
  • For traversing an ArrayList as well as Vector, Iterator or ListIterator can be used. That Iterator/ListIterator is fail-fast and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method.
    For Vector enumeration can also be used for traversing which is not fail-fast.

That's all for this topic Difference Between ArrayList And Vector in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between ArrayList And LinkedList in Java
  2. Difference Between Array And ArrayList in Java
  3. Difference Between ArrayList And CopyOnWriteArrayList in Java
  4. How to Remove Elements From an ArrayList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How to Sort HashSet in Java
  3. Difference Between Comparable and Comparator in Java
  4. Polymorphism in Java
  5. Array in Java With Examples
  6. finalize method in Java
  7. Nested Try Statements in Java Exception Handling
  8. Spring Boot Event Driven Microservice With Kafka

Tuesday, January 2, 2024

How to Sort an ArrayList in Descending Order in Java

In Java ArrayList elements are added in sequential order and while iterating an ArrayList same sequential order will be used to retrieve the elements. Sometimes you may have a requirement to sort an ArrayList in ascending or descending order. In this post we'll see how to sort an ArrayList in descending order in Java.

Sorting ArrayList in descending order

For sorting ArrayList in descending order in Java there are following options

  1. Use method reverseOrder() provided by Collections class. See example.
  2. General form and description

    public static <T> Comparator<T> reverseOrder()
    

    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

    There is also a Comparator.reverseOrder() method Java 8 onward that can also be used.

  3. Using a custom comparator. See example.

  4. You can also sort Java ArrayList in descending order using Java Stream API's sorted() method and then collect it into a separate List. That way you can retain the original list. See example.

You must also know about the overloaded sort method provided by the Collections class.

  • public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).

Sorting ArrayList Using reverseOrder method

reverseOrder() method mentioned above can be provided as the second parameter in the sort() method mentioned above and you will get the ArrayList sorted in reverse order. Let's see an example.

In the program Collections.reverseOrder() method is passed as an argument to the Collections.sort() method to sort ArrayList in reverse order.

public class SortListDemo {
  public static void main(String[] args) {
    // Using diamond operator (Right side no type specified)
    // Available from Java7 onwards
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // sorting the list in descending order
    Collections.sort(cityList, Collections.reverseOrder());
    //Displaying the list
    for(String city : cityList){
      System.out.println("Name " + city);
    }
  }
}

Output

Name Mumbai
Name Mumbai
Name Kolkata
Name Delhi
Name Chennai
Name Bangalore

Java 8 onward there is also a Comparator.reverseOrder() method that can be used to sort an ArrayList in descending order in Java.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
    cityList.sort(Comparator.reverseOrder());
    System.out.println(cityList);

  }
}

Sorting Java ArrayList Using custom Comparator

Internally reverseOrder method calls a Comparator class to do the sorting in reverse order. You can do it yourself too by writing your own comparator class. Writing your own Comparator gives you more control over the object ordering.

public class SortListDemo {
  public static void main(String[] args) {
    // Using diamond operator (Right side no type specified)
    // Available from Java7 onwards
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // sorting the list in descending order
    Collections.sort(cityList, new MyComparator());
    //Displaying the list
    for(String city : cityList){
      System.out.println("Name " + city);
    }
  }
}

//Custom comparator class
class MyComparator implements Comparator<String>{
  @Override
  public int compare(String o1, String o2) {
    return o2.compareTo(o1);
  }    
}

Sorting Java ArrayList Using Java Stream sorted()

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortListDemo {
  public static void main(String[] args) {
    
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
   
    List<String> sortedList = cityList.stream()
                                      .sorted(Comparator.reverseOrder())
                                      .collect(Collectors.toList());
    System.out.println(sortedList);
  }
}

That's all for this topic How to Sort an ArrayList in Descending Order in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. How LinkedList Class Works Internally in Java
  5. CopyOnWriteArrayList in Java - The thread safe variant of ArrayList

You may also like-

  1. How HashMap Works Internally in Java
  2. Difference Between CountDownLatch And CyclicBarrier in Java
  3. Java Phaser With Examples
  4. Varargs (Variable-length Arguments) in Java
  5. What if run() method called directly instead of start() method
  6. static reference to the non-static method or field error
  7. Method overloading in Java
  8. Creating Custom Exception Class in Java

Monday, January 1, 2024

Difference Between Array And ArrayList in Java

Difference between Array and ArrayList in Java is one question you may come across in a Java technical interview. Though performance wise both Array and ArrayList may give almost similar performance but functionality wise they both are used in quite different scenarios.

In this post we'll see some of the differences between ArrayList and Array in terms of how they are initialized and the performance they give.

Array Vs ArrayList in Java

  1. First and the most important difference is Array is static and can't be resized once declared.
    Whereas ArrayList is dynamic and that is why also known as dynamic array. ArrayList also uses array of Object internally, but it has the logic to keep growing the size of the array as and when previous size is not able to fit in the number of elements stored in the ArrayList.
  2. Refer: How ArrayList works internally in Java to know more about the internal implementation of ArrayList.

  3. Array can store both primitive types as well as objects whereas ArrayList can store only objects. Though Autoboxing and Unboxing has blurred that difference, but the important point to note here is that in case of ArrayList any primitive data type is still wrapped and stored as an Object.

    For example, if you want an array of primitive type int-

    int[] intArray = new int[3];
    

    Or, if you have a class Employee and you want an array of size 5 to hold 5 Employee objects then-

    Employee[] employees = new Employee[5];
    

    In case of ArrayList if you want to store integers then you have to do this, note the use of wrapper class Integer-

    List<Integer> myList = new ArrayList<Integer>();
    
  4. Difference number 2 between array and ArrayList also indicates one more difference, which is about "type safety". Since Array knows the type of the data which it can hold so it will give compiler error "Type Mismatch" or "ArrayStoreException" if it is not able to resolve it at run time. For example following code throws ArrayStoreException.
    Object[] names = new String[3];
    names[0] = 12;
    
    Where as following code throws compile time error "Type Mismatch".
    String[] names = new String[3];
    names[0] = 12;
    

    In case of ArrayList, generics brought the much needed type safety which, as shown above, is not required for Array as type of elements stored in the array is specified at the array creation time itself, trying to store element of any other type will result in ArrayStoreException.

    If a list, which stores only Integers, is needed it should be defined as-

    List<Integer> myList = new ArrayList<Integer>();
    
  5. Performance wise both Array and ArrayList are almost similar as ArrayList also uses array of Objects internally and both are index based. But there is some overhead in case of ArrayList if there are more elements and the internal array has to be resized.
    Since ArrayList stores only objects so memory usage is also more than the array.
  6. Array has length variable which gives the length of the array. Note that length attribute denotes the length of the array at the time of declaration.
    For example, If an array is declared like this-
    String[] names = new String[3];
    names[0] = "Java";
    
    Then length var will always be 3 even if array names has only one value.

    In case of ArrayList, size() method is used and it will give the size as the current number of elements in the ArrayList.

That's all for this topic Difference Between Array And ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between ArrayList And LinkedList in Java
  2. Difference Between ArrayList And Vector in Java
  3. Difference Between ArrayList And CopyOnWriteArrayList in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. TreeMap in Java With Examples
  3. Polymorphism in Java
  4. Method overriding in Java
  5. Race condition in Java multi-threading
  6. Java ThreadLocal Class With Examples
  7. Lambda expression and exception handling
  8. Dependency Injection in Spring Framework

Thursday, October 27, 2022

removeIf() Method in Java Collection With Examples

In this post we'll see how to use removeIf() method to remove elements from the Collection that satisfy the given condition. The removeIf() method is included in java.util.Collection interface in Java 8. Since it is part of Collection interface so you can use it with Collections like ArrayList, HashSet that implements Collection interface. To use it with HashMap you will have to get a collection view of the Map, since Map doesn't implement Collection interface.


Java removeIf() method syntax

boolean removeIf(Predicate<? super E> filter)

Parameter passed to this method is of type Predicate functional interface, which can be implemented as a boolean-valued function with one argument.

Method returns true if any elements were removed.

Removing elements from ArrayList using removeIf() method

In this example we'll have a list of cities and we'll remove elements from this ArrayList using removeIf() method. In passed Predicate if the condition holds true for any of the elements, then that element is removed from the list.

import java.util.ArrayList;
import java.util.List;

public class RemoveIf {

  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    System.out.println("*** List Initially ***");
    System.out.println(cityList);
    cityList.removeIf(p -> p.equalsIgnoreCase("Hyderabad") || 
          p.equalsIgnoreCase("Bangalore"));
    System.out.println("After Removal " + cityList);
  }
}

Output

*** List Initially ***
[Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]
After Removal [Delhi, Mumbai, Kolkata, Mumbai]

Removing elements from HashSet using removeIf() method

You can use removeIf() method with HashSet also to remove elements from the Set based on the passed condition. In the given example condition is to remove cities having name of length more than 6.

import java.util.HashSet;
import java.util.Set;

public class RemoveIf {

  public static void main(String[] args) {
    // creating a HashSet
    Set<String> citySet = new HashSet<String>();
    // Adding elements
    citySet.add("London");        
    citySet.add("Tokyo");
    citySet.add("New Delhi");
    citySet.add("Beijing");
    citySet.add("Nairobi");
    System.out.println("*** Set Initially ***");
    System.out.println(citySet);
    
    // Remove all cities having length more than 6
    citySet.removeIf(e -> e.length() > 6);
    System.out.println("After Removal " + citySet);
  }
}

Output

*** Set Initially ***
[Beijing, New Delhi, Nairobi, Tokyo, London]
After Removal [Tokyo, London]

Removing elements from HashMap using removeIf() method

To use removeIf() method with a Map you have to get Collection view of a Map. After getting the Collection view of a Map removeIf() method can be used.

import java.util.HashMap;
import java.util.Map;


public class RemoveIf {

  public static void main(String[] args) {
    Map<String, String> cityMap = new HashMap<String, String>();
    // Adding elements
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Beijing");
    cityMap.put("5", "Berlin");

    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    // Use entrySet to get Set view of all Map entries. 
    // Remove entry from Map based on the condition for value.
    cityMap.entrySet().removeIf(entry -> entry.getValue().equals("Beijing"));
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Beijing, 5=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai, 5=Berlin}

That's all for this topic removeIf() Method in Java Collection With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Entry From HashMap in Java
  2. How to Remove Elements From an ArrayList in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Java Map replace() With Examples
  5. HashSet Vs LinkedHashSet Vs TreeSet in Java

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. CopyOnWriteArraySet in Java With Examples
  3. Switch Expressions in Java 12
  4. Java Nested Class And Inner Class
  5. Reading File in Java Using Files.lines And Files.newBufferedReader
  6. Angular Cross Component Communication Using Subject Observable
  7. Angular HttpClient - Set Response Type as Text
  8. Spring Web MVC Tutorial

Wednesday, October 26, 2022

How to Remove Elements From an ArrayList in Java

To remove elements from an ArrayList in Java you have the following options.

  • You can use remove() method provided by ArrayList class to remove an object from ArrayList.
  • You can use remove() method provided by Iterator.
  • There is a removeIf() method too in ArrayList class that can be used Java 8 onwards to remove elements from ArrayList in Java.

In this post we'll see when to use which method and why.


ArrayList remove() method

ArrayList provides two overloaded remove methods for removing element from an ArrayList in Java-

  • remove(int index)- This method takes int (which specifies the index in the list) as parameter and removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
  • public boolean remove(Object o)- This method takes the object, which has to be removed as parameter and removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged.

If you are just removing an element from an ArrayList without looping the list then you can remove an element by giving its index in the list or specifying the object itself.

import java.util.ArrayList;
import java.util.List;

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    System.out.println("Original List- " + cityList);
    cityList.remove(1);
    
    cityList.remove("Mumbai");
    System.out.println("List after removing elements- " + cityList);
  }
}

Output

Original List- [Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]
List after removing elements- [Delhi, Kolkata, Hyderabad, Bangalore]

Removing element from ArrayList while iterating the list

Note that using ArrayList's remove method with enhanced for loop or iterator may result in ConcurrentModificationException as the iterators returned by ArrayList class's iterator and ListIterator methods are fail-fast. Which means if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)

Example code

Here is an example where ArrayList's remove() method is used while iterating a list using For-Each loop. As you can see ConcurrentModificationException is thrown.

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
               
    for(String city : cityList){
      if(city.equalsIgnoreCase("Kolkata"))
        cityList.remove(city);
    }
  }
}

Output

Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
 at java.util.ArrayList$Itr.next(Unknown Source)
 at org.netjs.prog.RemoveFromListDemo.main(RemoveFromListDemo.java:20)

Using Iterator's remove method to remove element from ArrayList

While looping if you want to remove any element from an ArrayList you should use use Iterator's remove method so that ConcurrentModificationException is not thrown.

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
                
    Iterator<String> itr = cityList.iterator();
    int i = 0;
    while(itr.hasNext()){
      System.out.println("city " + itr.next());
      if(i == 3 || i == 4){
        itr.remove();
      }
      i++;
    }
    
    System.out.println("After deletion " );
    for(String city : cityList){
      System.out.println("city " + city);
    }
  }
}

Output

city Delhi
city Mumbai
city Kolkata
city Hyderabad
city Bangalore
city Mumbai
After deletion 
city Delhi
city Mumbai
city Kolkata
city Mumbai

Using ArrayList's remove() method with normal for loop

ArrayList's remove method can be used with normal for loop to remove an ArrayList in Java. If index is passed then it may give undesired result because of the fact that all the other elements are shifted to the left when an element is removed.
As example In the given program code if I want to remove the elements at index 3 & 4 then ideally Hyderabad and Bangalore should be removed from the list. Let's see what happens-

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    
    for(int i = 0; i < cityList.size(); i++){
      if(i == 3 || i == 4){
        cityList.remove(i);
      }
    }
    
    System.out.println("After deletion " );
    for(String city : cityList){
      System.out.println("city " + city);
    }
  }
}

Output

After deletion 
city Delhi
city Mumbai
city Kolkata
city Bangalore

It can be seen that Hyderabad is removed alright but Mumbai is removed instead of Bangalore. This happened because after Hyderabad is removed elements in the list are shifted and Bangalore came in the place of Hyderabad and Mumbai in place of Bangalore. Thus Mumbai was at index 4 hence removed.

In the previous code if we were using city(object) in the if condition then it would have run fine.

public class RemoveFromListDemo {

  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    
    for(int i = 0; i < cityList.size(); i++){
      String city = cityList.get(i);
      if(city.equalsIgnoreCase("Kolkata") || city.equalsIgnoreCase("Bangalore")){
        cityList.remove(city);
      }
    }    
    System.out.println("After deletion " + cityList);
  }
}

Output

After deletion [Delhi, Mumbai, Hyderabad, Mumbai]

Using removeIf() to remove element from ArrayList

If you are using Java 8, then removeIf() method can be used to remove element from ArrayList, which takes Predicate functional interface as a parameter. In that case we can write the removal code with in one line as-

cityList.removeIf(p -> p.equalsIgnoreCase("Hyderabad") || 
    p.equalsIgnoreCase("Bangalore"));

ArrayList remove method and AutoBoxing problem

While removing elements from an ArrayList of Integers we may get problem because of Autoboxing. As already mentioned there are two overloaded remove methods-

  • Remove(int index)
  • Remove(Object o)

If we give an int as parameter then it will always be treated as a call to remove method with int parameter.
Let's clear it with an example

public class RemoveFromListDemo {
  public static void main(String[] args) {
    
    List<Integer> numberList = new ArrayList<Integer>();
    // adding to list as int, no need to do
    // new Integer(1)
    numberList.add(1);
    numberList.add(2);
    numberList.add(3);
    numberList.add(4);
    
    // Removing by index 1
    numberList.remove(1);
    // This time removing the integer Object 4
    numberList.remove(4);
  }
}

Output

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
 at java.util.ArrayList.rangeCheck(Unknown Source)
 at java.util.ArrayList.remove(Unknown Source)
 at org.netjs.prog.RemoveFromListDemo.main(RemoveFromListDemo.java:20)

So, even if a user thinks while removing the second time that he is giving an object as parameter and hoping autoboxing will take care of all the wrapping to Integer Object chore it won't happen in this case. Second call will also be treated as a call to remove method with int parameter. First remove has already removed one element so now the list size is 3 and trying to access index 4 in such a list will throw IndexOutOfBoundsException.

So in this case user has to explicitly tell the compiler that remove method which takes object as parameter has to be called.

numberList.remove(new Integer(4)); 

That's all for this topic How to Remove Elements From an ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Remove Duplicate Elements From an ArrayList in Java
  3. How to Sort ArrayList in Java
  4. How to Join Lists in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. equals() And hashCode() Methods in Java
  2. How HashSet Works Internally in Java
  3. ConcurrentHashMap in Java With Examples
  4. Interface Static Methods in Java 8
  5. Method reference in Java 8
  6. Functional Interfaces in Java
  7. Static Synchronization in Java Multi-Threading
  8. java.lang.ClassCastException - Resolving ClassCastException in Java

Wednesday, September 14, 2022

ListIterator in Java

In this post we'll see another way to iterate a List using ListIterator in Java.

Though there is already an iterator provided for the list, which will iterate sequentially through all the elements in a list but it is uni-directional.

List iteration in Java

Iteration of a list

If you are iterating this ArrayList you can only go from left to right. If you have any such requirement where you want to iterate the list in both directions you can use ListIterator. ListIterator in Java provides next() and previous() methods to iterate in both forward and backward directions.


No current element in ListIterator

The interesting point about Listiterator in Java is that it has no current element. Its current cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions.

ListIterator in Java

Iterating a list using list iterator

Java ListIterator methods summary

Following is the list of methods in the ListIterator class in Java.
  1. add(E e)- Inserts the specified element into the list (optional operation).
  2. hasNext()- Returns true if this list iterator has more elements when traversing the list in the forward direction.
  3. hasPrevious()- Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  4. next()- Returns the next element in the list and advances the cursor position.
  5. nextIndex()- Returns the index of the element that would be returned by a subsequent call to next().
  6. previous()- Returns the previous element in the list and moves the cursor position backwards.
  7. previousIndex()- Returns the index of the element that would be returned by a subsequent call to previous().
  8. remove()- Removes from the list the last element that was returned by next() or previous() (optional operation).
  9. set(E e)- Replaces the last element returned by next() or previous() with the specified element (optional operation).

Note that the remove() and set(object) methods are not defined in terms of the cursor position, they are defined to operate on the last element returned by a call to next() or previous().

ListIterator Java example with list iteration in both directions

public class ListIteratorDemo {
  public static void main(String[] args) {
    List<Integer> numberList = new ArrayList<Integer>();
    ListIterator<Integer> ltr = null;
    numberList.add(25);
    numberList.add(17);
    numberList.add(108);
    numberList.add(76);
    numberList.add(2);
    numberList.add(36);
    ltr = numberList.listIterator();
    //forward iteration
    System.out.println("Iterating list in forward direction");
    while(ltr.hasNext()){
      System.out.println(ltr.next());
    }
    // backward iteration 
    System.out.println("Iterating list in backward direction");
    while(ltr.hasPrevious()){
      System.out.println(ltr.previous());
    }
  }
}

Output

Iterating list in forward direction
25
17
108
76
2
36
Iterating list in backward direction
36
2
76
108
17
25

Here we are first going forward using next() method. When the forward iteration is done cursor is after the last element so we can go backward using previous method() till the start of the list and that's what is done in the code.

Points to note

  • ListIterator in Java provides an add(E e) method which is not there in Iterator. add(E e) inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any.
  • ListItearator also provides set method. void set(E e) replaces the last element returned by next() or previous() with the specified element (optional operation). This call can be made only if neither remove() nor add(E) have been called after the last call to next or previous.
  • ListIterator is fail-fast and throws a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add methods.

That's all for this topic ListIterator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Loop or Iterate an Arraylist in Java
  3. How to Sort an ArrayList in Descending Order in Java
  4. Difference Between ArrayList And LinkedList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How HashSet Works Internally in Java
  2. Method Reference in Java
  3. Find All Permutations of a Given String Java Program
  4. Synchronization in Java - Synchronized Method And Block
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Varargs (Variable-length Arguments) in Java
  7. Covariant Return Type in Java
  8. Java Multithreading Interview Questions And Answers

Sunday, August 7, 2022

Unmodifiable or Immutable List in Java

A List is considered unmodifiable if elements cannot be added, removed, or replaced from the list once the unmodifiable instance of a List is created. In this post we’ll see how Unmodifiable list was created before Java 9 and how it can be created Java 9 onward using Immutable List Static Factory Methods.


Creating Unmodifiable list before Java 9

Before Java 8, in order to create unmodifiable list Collections.unmodifiableList() method was used.

  • Collections.unmodifiableList(List<? extends T> list)- Returns an unmodifiable view of the specified list. Note that the list underneath can still be modified.
public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = new ArrayList<>();
    alphaList.add("a");
    alphaList.add("b");
    alphaList.add("c");
    alphaList.add("d");
    //List<String> alphaList = Arrays.asList("a", "b", "c", "d");
    List<String> aList = Collections.unmodifiableList(alphaList);
    alphaList.add("e");
    System.out.println("alphaList- " + alphaList);
    aList.add("f");
  }
}

Output

alphaList- [a, b, c, d, e]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1058)
 at org.netjs.Programs.UnmodifiedList.main(UnmodifiedList.java:20)

As you can see alphaList which is used to create unmodifiable list can still be modified though changing the unmodifiable list results in UnsupportedOperationException.

By using Arrays.asList to create list you can ensure that methods that change the size of the list can’t be called on the returned list.

public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = Arrays.asList("a", "b", "c", "d");
    List<String> aList = Collections.unmodifiableList(alphaList);
    alphaList.add("e");
    System.out.println("alphaList- " + alphaList);
    aList.add("f");
  }
}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.AbstractList.add(AbstractList.java:153)
 at java.base/java.util.AbstractList.add(AbstractList.java:111)
 at org.netjs.Programs.UnmodifiedList.main(UnmodifiedList.java:13)

As you can see now the original list itself can’t call any size changing operation.

Creating Unmodifiable list in Java 9

The List.of (added in Java 9) and List.copyOf (added in Java 10) static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics-

  1. The collections returned by the convenience factory methods added in JDK 9 are conventionally immutable. Elements cannot be added, removed, or replaced from such a list. Elements cannot be added, removed, or replaced from such a list. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown.
  2. If the elements with in the list themselves are mutable, this may cause the List's contents to appear to change.
  3. Such lists can't be created with null elements any such attempt result in NullPointerException.
  4. Unmodifiable lists are serializable if all elements are serializable.
  5. The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.

List.of() method in Java

List.of() method static factory method is a convenient way to create unmodifiable lists Java 9 onward. This method has both fixed-argument form and varargs form. Fixed-argument form overloads up to 10 elements and the form of these method is as follows.

List.of(E e1)- Returns an unmodifiable list containing one element.

..

..

List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)- Returns an unmodifiable list containing nine elements. 

List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)- Returns an unmodifiable list containing ten elements.

varargs form

  • List.of(E... elements)- Returns an unmodifiable list containing an arbitrary number of elements.

List.of() method Java example

public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = List.of("a", "b", "c", "d");
    System.out.println("alphaList- " + alphaList);
    // raises error
    alphaList.add("e");
  }
}

Output

alphaList- [a, b, c, d]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
 at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:76)
 at org.netjs.Programs.UnmodifiedList.main(UnmodifiedList.java:10)

List.copyOf() method in Java

If you want to create an unmodifiable List using an existing collection then you can use copyOf() method.

  • List.copyOf(Collection<? extends E> coll)- Returns an unmodifiable List containing the elements of the given Collection, in its iteration order. The given Collection must not be null, and it must not contain any null elements. If the given Collection is subsequently modified, the returned List will not reflect such modifications.

List.copyOf() method Java example

public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = new ArrayList<>();
    alphaList.add("a");
    alphaList.add("b");
    alphaList.add("c");
    alphaList.add("d");
    List<String> aList = List.copyOf(alphaList);
    alphaList.add("e");
    System.out.println("alphaList- " + alphaList);
    System.out.println("aList- " + aList);
  }
}

Output

alphaList- [a, b, c, d, e]
aList- [a, b, c, d]

As you can see even if the original collection is modified the returned unmodifiable list doesn’t reflect such modification.

That's all for this topic Unmodifiable or Immutable List in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Duplicate Elements From an ArrayList in Java
  2. How to Sort a HashMap in Java
  3. HashSet in Java With Examples
  4. CopyOnWriteArrayList in Java With Examples
  5. Java Collections Interview Questions And Answers

You may also like-

  1. AtomicInteger in Java With Examples
  2. Java ScheduledThreadPoolExecutor - Task Scheduling in Java
  3. Livelock in Java Multi-Threading
  4. Reflection in Java - Getting Constructor Information
  5. Java Pass by Value or Pass by Reference
  6. Difference Between Encapsulation And Abstraction in Java
  7. String Slicing in Python
  8. Difference Between @Controller And @RestController Annotations in Spring

Friday, July 1, 2022

How to Join Lists in Java

Sometimes we do have a need to join the lists constructed through different queries or received through different sources. This post shows different ways to join lists in Java which are as given below.

  1. Joining two lists in Java without using any API
  2. Joining lists in Java using addAll() method
  3. Joining lists using Apache Commons Collections

Joining two lists in Java without using any API

First thing that comes to mind in this scenario is loop the second list, retrieve the elements from the second list and add them to the first list thus creating a merged list. Some thing like this-

List<String> cityList = new ArrayList<String>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Kolkata");
List<String> anotherCityList = new ArrayList<String>();
anotherCityList.add("Hyderabad");
anotherCityList.add("Bangalore");
anotherCityList.add("Mumbai");    
for(int i = 0; i < anotherCityList.size() ; i++){
  cityList.add(anotherCityList.get(i));
}
for(String cityName : cityList){
  System.out.println("City Name " + cityName);
}

But why even write a loop and add elements one by one when there are better options to join lists in Java.

  • Using addAll() method provided by List interface.
  • Using ListUtils.union() method provided by Apache Commons Collections.

Joining lists in Java using addAll() method

You can use addAll() method to merge multiple lists. You can pass the list as an argument to the method to join it at the end of another list.

addAll​(Collection<? extends E> c)- addAll method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

public class JoinListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    List<String> anotherCityList = new ArrayList<String>();
    anotherCityList.add("Hyderabad");
    anotherCityList.add("Bangalore");
    anotherCityList.add("Mumbai");
    
    // Using addAll method, here adding with in the first list
    // we can create a new list and use addAll method to 
    // add both lists to the new List
    cityList.addAll(anotherCityList);
    System.out.println("--Merged List--");
    for(String cityName : cityList){
      System.out.println("City Name " + cityName);
    }
  }
}

Output

--Merged List--
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

Here addAll method is used to append second list to the first list, if there is a requirement that original lists should not be altered then you can create a new list and use addAll method to add both the lists to a new list.

Joining lists using Apache Commons Collections

Another way to join lists in Java is using ListUtils class in Apache Commons Collections. Only thing you need is to add commons-collections jar to your project. ListUtils class has a static method union to merge two lists.

According to the description of this method -

Returns a new list containing the second list appended to the first list. The List.addAll(Collection) operation is used to append the two given lists into a new list.

General form of union method

public static java.util.List union(java.util.List list1, java.util.List list2)

Though the name "union" may suggest otherwise please note that it will retain the duplicate elements in both the lists.

Let's see example code using this option to merge two (or more) lists in Java-

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;

public class JoinListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    List<String> anotherCityList = new ArrayList<String>();
    anotherCityList.add("Hyderabad");
    anotherCityList.add("Bangalore");
    anotherCityList.add("Mumbai");
    
    // Using ListUtils.union
    List<String> newCityList = ListUtils.union(cityList, anotherCityList);
    System.out.println("--Merged List--");
    for(String cityName : newCityList){
      System.out.println("City Name " + cityName);
    }
  }
}

Output

--Merged List--
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

You can see that duplicates are retained when the union method is used. Name of the method union is a bit misleading as generally it suggests that duplicates will be counted once.

That's all for this topic How to Join Lists in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How LinkedList Class Works Internally in Java
  3. How and Why to Synchronize ArrayList in Java
  4. How to Remove Duplicate Elements From an ArrayList in Java
  5. How to Sort ArrayList in Java

You may also like-

  1. How HashMap Works Internally in Java
  2. How HashSet Works Internally in Java
  3. Covariant Return Type in Java
  4. Association, Aggregation And Composition in Java
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Deadlock in Java Multi-Threading
  7. Synchronization in Java - Synchronized Method And Block
  8. Interface Default Methods in Java

Sunday, May 15, 2022

How to Convert Array to ArrayList in Java

There may be a scenario when you want to convert an array to an ArrayList in Java in order to use some of the methods provided by ArrayList in Java. As example using contains() method provided by List to check if an element is there in the list.

Some of options you have to convert Array to ArrayList in Java are as follows.

  1. Arrays.asList(T... a) method that returns a fixed-size list backed by the specified array. One problem with using this option is that the returned list is static and trying to modify it will result in UnsupportedOperationException. See example.
  2. Using Collections.addAll​(Collection<? super T> c, T... elements) where elements to be added to the collection can be passed as an array. The List you get by using this method is independent of the array making it a better choice for conversion of array to ArrayList. See example.
  3. Another option to convert array to ArrayLIst is using the collect method of the Java Stream API from Java 8 onward. See example.

Converting array to ArrayList using Arrays.asList() method

Arrays class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The method to convert Array to ArrayList is asList() whose general form is

public static <T> List<T> asList(T... a)

In the following Java code there is an array of cities which is converted to an ArrayList.

public class CovertToArrayList {
  public static void main(String[] args) {
    String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
    //Converting array to List
    List<String> cityList = Arrays.asList(cityArray);
    for(String name : cityList){
      System.out.println("City : " + name);
    } 
  }
}

There are few points to note about Arrays.asList() method

  • This method returns a List that is a view onto the array. You can say it is more of a wrapper around an array. That makes it more efficient than any other option as array elements are not actually copied to the List.
  • The list returned by this method is a fixed-size list.
  • Since list returned is just a view onto the array, if you change any element in the list that change is reflected in the array too.
  • The ArrayList class used to create the list while using this method Arrays.asList is actually a static class within the Arrays class and many of the methods of the original ArrayList are not supported by this ArrayList. As example add() method is not there in this ArrayList so any attempt to add new element to the returned list will throw UnsupportedOperationException. Following example shows the same.
public class CovertToArrayList {
  public static void main(String[] args) {
    String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
    //Converting array to List
    List<String> cityList = Arrays.asList(cityArray);
    // Attempt to add new element in the list
    // This will throw exception
    cityList.add("Pune");
    for(String name : cityList){
      System.out.println("City : " + name);
    }        
  }
}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(Unknown Source)
 at java.util.AbstractList.add(Unknown Source)
 at org.netjs.prog.CovertToArrayList.main(CovertToArrayList.java:16)
  • You can also initialize a List using Arrays.asList() method like this
    List<String> cityList = Arrays.asList("Delhi", "Mumbai", "Bangalore", 
    "Hyderabad", "Chennai");
    
  • As stated above no new element can be added to the List returned by Arrays.asList method. If you have to add new elements to the List returned using asList method then you need to wrap the list returned by Arrays.asList to a new ArrayList after conversion of array to ArrayList.

    Wrapping the list returned by Arrays.asList to a new ArrayList

    public class CovertToArrayList {
      public static void main(String[] args) {
        String cityArray[] = {"Delhi", "Mumbai", "Bangalore", 
                             "Hyderabad", "Chennai"};
        //Converting array to List
        ArrayList<String> cityList = new ArrayList<String>(
                                            Arrays.asList(cityArray));
        cityList.add("Pune");
        for(String name : cityList){
          System.out.println("City : " + name);
        }     
      }
    }
    

    Output

    City : Delhi
    City : Mumbai
    City : Bangalore
    City : Hyderabad
    City : Chennai
    City : Pune
    

    It can be seen that now new elements can be added to the list.

    Converting Array to ArrayList in Java using Collections.addAll method

    In this option to convert array to ArrayList using Collections.addAll() method both array and ArrayList are passed as parameters to this method and the elements of array are added to the passed ArrayList. ArrayList you get from this method is independent from the array and can be modified without the change reflecting onto array and with out throwing any exception.

    public class CovertToArrayList {
      public static void main(String[] args) {
        String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
        List<String> cityList= new ArrayList<String>();
        Collections.addAll(cityList, cityArray);
        cityList.add("Pune");
        for(String name : cityList){
          System.out.println("City : " + name);
        }        
      }
    }
    

    Convert Array to ArrayList using Stream API collect() method

    Stream API in Java gives you another option to convert Array to ArrayList by using collect() method.

    public class CovertToArrayList {
      public static void main(String[] args) {
        String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
        // Using stream to convert array to ArrayList
        List<String> cityList = Stream.of(cityArray).collect(Collectors.toList());
        cityList.add("Pune");
        for(String name : cityList){
          System.out.println("City : " + name);
        }        
      }
    }
    

    Output

    City : Delhi
    City : Mumbai
    City : Bangalore
    City : Hyderabad
    City : Chennai
    City : Pune
    

    That's all for this topic How to Convert Array to ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


    Related Topics

    1. How to convert ArrayList to Array in Java
    2. How ArrayList works internally in Java
    3. How to remove duplicate elements from an ArrayList in Java
    4. How to Join Lists in Java
    5. Java Collections Interview Questions And Answers

    You may also like-

    1. TreeMap in Java With Examples
    2. Difference Between sleep And wait in Java Multi-Threading
    3. Java Stream - Collectors.groupingBy() With Examples
    4. Automatic numeric type promotion in Java
    5. Marker Interface in Java
    6. Difference Between Checked And Unchecked Exceptions in Java
    7. Method Reference in Java
    8. How to Fix The Target Type of This Expression Must be a Functional Interface Error

    Saturday, May 14, 2022

    How to Convert ArrayList to Array in Java

    While working with ArrayList, there may be a need to get the actual array that holds the elements of the list. This conversion of ArrayList to array in Java may be required because-

    • You have to pass the List to some third party method which takes array as parameter.
    • For faster processing of certain operations.

    Converting ArrayList to Array in Java by looping

    Well there is always brute force approach to loop through the list, get the elements of the list using get method and assign them to array.

    public class ConvertArray {
      public static void main(String[] args) {
        List<String> cityList = new ArrayList<String>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Hyderabad");
        cityList.add("Chennai");
        
        // Create an array of the same size as list
        String cityArray[] = new String[cityList.size()];   
        
        // Loop through the list and assign values to array
        for(int i =0; i < cityList.size(); i++){
          cityArray[i] = cityList.get(i);
        }
        
        //Displaying Array values
        for(String name : cityArray)
        {
          System.out.println("City : " + name);
        }
      }
    }
    

    Output

    City : Delhi
    City : Mumbai
    City : Bangalore
    City : Hyderabad
    City : Chennai
    

    Better approach for converting ArrayList to Array in Java

    There is another option provided by Collection interface itself. Within Collection interface there are two versions of toArray() method which can be used to convert ArrayList to array.

    • Object[] toArray()
    • <T> T[] toArray(T array[])

    The first version returns an array of Object. The second version returns an array containing the elements of the same type as list. Normally we go with the second version because it returns the array of the same type as List.

    Let's see the same example as above with the second version of toArray() to convert an ArrayList to array in Java.

    public class ConvertArray {
      public static void main(String[] args) {
        List<String> cityList = new ArrayList<String>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Hyderabad");
        cityList.add("Chennai");
        
        // Create an array of the same size as list
        String cityArray[] = new String[cityList.size()];   
        
        cityArray = cityList.toArray(cityArray);
        
        //Displaying Array values
        for(String name : cityArray)
        {
          System.out.println("City : " + name);
        }
      }
    }
    

    So that's how we can get an array from ArrayList.

    That's all for this topic How to Convert ArrayList to Array in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


    Related Topics

    1. How to Convert Array to ArrayList in Java
    2. How ArrayList Works Internally in Java
    3. How and Why to Synchronize ArrayList in Java
    4. Difference Between ArrayList and LinkedList in Java
    5. Java Collections Interview Questions And Answers

    You may also like-

    1. equals() And hashCode() Methods in Java
    2. Race Condition in Java Multi-Threading
    3. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
    4. Java Automatic Numeric Type Promotion
    5. Java Pass by Value or Pass by Reference
    6. Creating Custom Exception Class in Java
    7. Functional Interfaces in Java
    8. How to Fix The Target Type of This Expression Must be a Functional Interface Error