Collections
Collection is special type of classes in that we can add
data and retrieve from it. It support some properties which is useful while
doing programming. These classes provide support for stack, queue, hash set,
array list. Collection classes present in System.Collections namespace.
ArrayList:
Arraylist size is not fixed. It grows dynamically. You can
use add and remove method for adding and removing item from arraylist. In
ArrayList we can add any type of data. It’s not fixed.
Example:
ArrayList arr = new
ArrayList();
arr.Add("abd");
arr.Add(12);
Stack Collection:
Stack is a collection of type LIFO means last in
first out collection. We can retrieve items from stack like first item can
remove at last.
There is Push method of stack to be used for adding
item in stack.
Example:
using System;
using System.Collections.Generic;
using System.Collections;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Stack<int>
stk = new Stack<int>();
stk.Push(1);
stk.Push(2);
stk.Push(3);
foreach (int i in stk)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Output:
3
2
1
Also we can use pop method to remove and also
return next element. Like below
int i= stk.Pop();
It removes and return last element in stack.
Queue Collection:
Queue is a FIFO collection means First-in-First-out
collection. In which order they are inserted in collection only that order
element get retrieved.
Example:
using System;
using System.Collections.Generic;
using System.Collections;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Queue<int>
que = new Queue<int>();
que.Enqueue(1);
que.Enqueue(2);
que.Enqueue(3);
foreach (int i in que)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Output:
1
2
3
In Queue we use Enqueue method to add element in
collection.
0 Comments