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

How to sort list in reverse order

To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method. 
List list = new ArrayList(); 
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp) 

What is difference between Arrays and ArrayList?

Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as : 
int [] intArray= new int[6]; 
intArray[7]   // will give ArraysOutOfBoundException. 
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime. 
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional. 
            int[][][] intArray= new int[3][2][1];   // 3 dimensional array 

How can Arraylist be synchronized without using Vector?

 Arraylist can be synchronized using: 
• Collection.synchronizedList(List list) 
Other collections can be synchronized: 
• Collection.synchronizedMap(Map map) 
• Collection.synchronizedCollection(Collection c) 

What is difference between ArrayList and vector?

Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. 
Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.