Collection in Jav1
Collection in Jav1
Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation, and deletion.
Stack:-
The stack is a linear data structure that is used to store the collection of
objects. It is based on Last-In-First-Out (LIFO). Java collection framework
provides many interfaces and classes to store the collection of objects. One of
them is the Stack class that provides different operations such as push, pop,
search, etc.
Collections.sort(vector name);
Example:-
import java.util.*;
class vv
v.addElement("ram");
v.addElement("sham");
v.addElement("gopal");
//v.clear();
Collections.sort(v);
System.out.println(v);
Out put:-
D:\ajpr>javac vv.java
D:\ajpr>java vv
vector sorting is
LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. In the case of a doubly linked list, we
can add or remove elements from both sides.
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
1. import java.util.*;
2. class LinkedList1{
3. public static void main(String args[]){
4.
5. LinkedList al=new LinkedList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output: Ravi
Vijay
Ravi
Ajay
ArrayList:-
Java ArrayList class uses a dynamic array for storing the elements. It is like
an array, but there is no size limit. We can add or remove elements anytime.
So, it is much more flexible than the traditional array.
Method Description
void add(int index, E It is used to insert the specified element at the specified
element) position in a list.
void clear() It is used to remove all of the elements from this list.
1. import java.util.*;
2. class ArrayListExample1{
3. public static void main(String args[]){
4. ArrayList list=new ArrayList();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Printing the arraylist object
10. System.out.println(list);
11. }
12. }
Output:
[Mango, Apple, Banana, Grapes]