Professional Documents
Culture Documents
Java Concepts 2
Java Concepts 2
Array once declared ,its size is fixed,we cannot change the size of an Array.To make an
expandable array we use Collection,which is an Interface.Therefore we cannot create its
object.So to implement a Collection,we use ArrayList.
ArrayList :
· It is a class which implements Collection (Interface) indirectly.So actually ArrayList (class)
implements List (interface),which extends Collection (interface).
But in Collection,we dont need to specify the type of the data to be stored.The datatype of
collection is by default "object".
But wat if we want to store only one type of data in our collection?
But 1.7 and later ,says when we mention datatype on LHS,then y to mention it on RHS :
Suppose if we want to add 8 in between 5 and 6,we cant do that now bcz Collection doesnt
work on the concept of "index".
So to solve this prblm,we make use of "List".It makes use of index to store the elements inside
it.
· There also is another concept of "Set".Set is an interface again(Cant create its objects).
· But Set contains only unique values,no duplicate values are allowed.
· What are the Similarities Between TreeSet and HashSet?
Both TreeSet and HashSet are classes belong to the collection hierarchy.Both TreeSet and
HashSet stores only unique elements.Both TreeSet and HashSet can be used to store and
manipulate many elements.Both TreeSet and HashSet do not maintain the inserted order.
· Map
There is another one called Map.This again is an interface.So a class is needed to implement this
interface.So that class is HashMap or u can use HashTable.
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes
the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now
generics force the java programmer to store a specific type of objects.
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
list.add(10);
list.add("10");
list.add(10);
list.add("hello");
list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
Vector: