Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Removing null elements from List in Java

In this tutorial lets see how to remove null elements from the given list by using java Collections. Basic we could think iterating through List and to delete all null elements. But by using Collections class it makes easy to remove all null elements. Lets see simple example to delete null elements from list.
Removing null elements from List in Java


public static void main(String[] args) {
 
 final List<Integer> list = new ArrayList<Integer>();
 Collections.addAll(list, 1,2,null,3,4,null,5,6,null,7,8,null,9);
 
 System.out.println("LIST SIZE : "+list.size()+ " - " + list);
 
 list.removeAll(Collections.singleton(null));
 
 System.out.println("LIST SIZE : "+list.size()+ " - " + list);
}



OUTPUT:


LIST SIZE : 13 - [1, 2, null, 3, 4, null, 5, 6, null, 7, 8, null, 9]
LIST SIZE : 9 - [1, 2, 3, 4, 5, 6, 7, 8, 9]


How to convert list to read-only list in Java?

 
By using Collections class we can convert List to read-only List. This can done by using Collections.unmodifiableList(list) function from Collections class. By this we can't add or remove any element from the List. Not only List we can make other Collection Objects like Map, Set also to read-only as like below.

Collections.unmodifiableMap(map);
Collections.unmodifiableSet(set);
Collections.unmodifiableSortedMap(sortedMap);
Collections.unmodifiableSortedSet(sortedSet);

Lets see small example how to convert list to read-only list.


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

public class ReadOnlyList {

 public static void main(String[] args) {
  
  List<String> list = new ArrayList<String>();
  list.add("java");
  list.add("discover");
  list.add("threads");
  list.add("oops");
  list.add("servlet");
  
  System.out.println("LIST : "+list);
  
  // Removing "oops" from from list
  list.remove(3);
  
  System.out.println("LIST : "+list);
    
  // Making list to read-only
  list = Collections.unmodifiableList(list);

  // trying to removing "threds" from list
  list.remove(2);
    
  System.out.println("LIST : "+list);
 }
}


OUTPUT:


LIST : [java, discover, threads, oops, servlet]
LIST : [java, discover, threads, servlet]
Exception in thread "main" java.lang.UnsupportedOperationException


If we seen in above program we have added 5 values in list and we have removed 1 value "oops" from the list. Next we have converted list to read-only list by using unmodifiableList() method. Later when we try to remove "discover" value it throws UnsupportedOperationException because of read-only list. Even we can't add any value to this list. 




Difference between ArrayList and Vector in Java

 

ArrayList and Vector are the important collection classes which used in Java. And also widely asked in interview about their difference and similarities between these 2 classes. Before looking into the difference and similarities between these two classes lets discuss some of the collection classes and interface in Java Collection framework. Below hierarchy diagram will give you the brief structure of the interface and classes in Collection framework like what are all the classes derived from different interface. 


Java Collections


Similarities:

  • Both ArrayList and Vector implements List interface.
  • Both ArrayList and Vector are ordered collection and allow duplicate and null values.
  • Both ArrayList and Vector are index based and values can retried by using index, which means internally it uses array as data structure to store the values. 
  • While initializing both ArrayList and Vector size will be 10 by default.


Differences: 

  • Vector is thread-safe and ArrayList is non thread-safe, which means Vector is synchronized and ArrayList is not. Suppose if we using any multi-threading or concurrent process then Vector will be best suited and other ways ArrayList will be best.
  • Performance wise Vector will be slow since its synchronized. 
  • Vector introduced in first version of JDK and from JDK 1.2 its merged with Java Collection framework and its implements List interface. Where as ArrayList introduced in JDK 1.2 along with Collection framework
  • By default both ArrayList and Vector increment the size automatically. The difference is ArrayList will increments its array size by half of its size, where as Vector will doubles the size of its array when its size is increased by default suppose if we didn't set the capacity Increment size.
  • Vector's capacity size increment can be set to any number when we initialize  where as ArrayList we can't. 


ArrayList initialize:

ArrayList<String> arr = new ArrayList<String>(); // Default initialCapacity = 10

ArrayList<String> arr = new ArrayList<String>(100); // initialCapacity = 100

Vector initialize:

Vector<String> vec = new Vector<String>(); // Default initialCapacity = 10

Vector<String> vec = new Vector<String>(100); // initialCapacity = 100

Vector<String> vec = new Vector<String>(100,10); // initialCapacity = 100 and capacityIncrement = 10


Vector and ArrayList

 
In this tutorial we will see about Vector and ArrayList in java. Both Vector and ArrayList shares common data structure "Array" internally.

Synchronized and non-synchronized
By default Vector is Synchronized and ArrayList is not Synchronized. By this for Thread safe we can use Vector and for non-thread safe we can use ArrayList. Even ArrayList can be converted to synchronized by Collections class using "Collections.synchronizedList(list)"


Vector in Collection API
Vector defined in first JDK version and later from Java 2 platform Vector got added with Java Collection API. Vector has been retrofitted to implement List Interface.
Once Vector added in Collection API, older methods in Vector class got updated to implement List Interface. Below are the methods got updated from Older version to new methods.


Old Vector MethodsNew Vector Methods
void addElement(Object)boolean add(Object)
boolean removeElement(Object)boolean remove(Object)
void removeElementAt(int)void remove(int)
void insertElementAt(Object, int)void add(index, Object)
Object elementAt(int)Object get(int)
Enumeration elements()Iterator iterator()
ListIterator listIterator()
void copyInto(Object[])Object[] toArray()
void removeAllElements()void clear()
void setElementAt(int)Object set(int, Object)


Where to use Vector and ArrayList
By performance wise ArrayList will be better in case of non synchronized operations and when we need for thread-safe operation then we need to opt for Vector.

Size
Both Vector and ArrayList will re-size dynamically. Vector will double the size of its array automatically when its full, where as ArrayList will increase by half of its array size.