Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of collection framework in java?

What is the need of Collection framework in Java since all the data operations(sorting/adding/deleting) are possible with Arrays and moreover array is suitable for memory consumption and performance is also better compared with Collections.

Can anyone point me a real time data oriented example which shows the difference in both(array/Collections) of these implementations.

like image 794
JavaUser Avatar asked Mar 23 '10 02:03

JavaUser


People also ask

What is collection What is need of it?

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

What are the collections used in framework?

Java Collections framework provides implementation classes for core collection interfaces. We can use them to create different types of collections in the Java program. Some important collection classes are ArrayList, LinkedList, HashMap, TreeMap, HashSet, and TreeSet.


2 Answers

  • Arrays are not resizable.
  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizeable array lists (like Vector but cooler), red-black trees, hash-based maps (like Hashtable but cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map, whether backed by a red-black tree or a hashtable.

In other words, Java Collections Framework allows you to use the right data structure, because one size does not fit all.

like image 83
Chris Jester-Young Avatar answered Nov 13 '22 12:11

Chris Jester-Young


Several reasons:

  • Java's collection classes provides a higher level interface than arrays.
  • Arrays have a fixed size. Collections (see ArrayList) have a flexible size.
  • Efficiently implementing a complicated data structures (e.g., hash tables) on top of raw arrays is a demanding task. The standard HashMap gives you that for free.
  • There are different implementation you can choose from for the same set of services: ArrayList vs. LinkedList, HashMap vs. TreeMap, synchronized, etc.
  • Finally, arrays allow covariance: setting an element of an array is not guaranteed to succeed due to typing errors that are detectable only at run time. Generics prevent this problem in arrays.

Take a look at this fragment that illustrates the covariance problem:

  String[] strings = new String[10];
  Object[] objects = strings;

  objects[0] = new Date();  // <- ArrayStoreException: java.util.Date
like image 29
Itay Maman Avatar answered Nov 13 '22 10:11

Itay Maman