top of page
Search
Writer's pictureAbhinaw Tripathi

LinkedHashSet Class and Stack Class Java


LinkedHashSet Class

This is a subclass of HashSet class and does not contain any additional members on its own.It is a generic class that has declaration:

class LinkedHashSet<T>

Here.T represents generic type parameter.

LinkedHashSet internally uses a linked list to store the elements.

Stack Class

A stack represents a group of elements stored in LIFO.This means that the element which is stored as a last element into the stack will be the first element to be removed from the stack.

There are three operation can be performed on stack:

  1. Push() ----Inserting an element in stack.

  2. Pop()------Deleting an element from stack.

  3. Peek()-----Searching an element from stack.

Stack Class Methods

  • boolean empty();

  • element peek();

  • element pop();

  • element push(element obj);

  • int search(Object obj);

What is Auto Boxing?

Ans: Converting a primitive data type into an object form automatically is called Auto-Boxing.Auto Boxing is done in generic types.

Program:

/**

*

*/

package com.collectionpack;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Stack;

/**

* @author Abhinaw.Tripathi

*

*/

public class StackApp

{

/**

* @param args

* @throws IOException

* @throws NumberFormatException

*/

public static void main(String[] args) throws NumberFormatException, IOException

{

Stack<Integer> st=new Stack<>();

int choice = 0;

int position,element;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

while(choice < 4)

{

System.out.println("Stack Operation");

System.out.println("1 Push an element");

System.out.println("2 Pop an element");

System.out.println("3 Search an element?");

System.out.println("4 Exist");

choice=Integer.parseInt(br.readLine());

switch (choice)

{

case 1:

System.out.println("Enter element: ");

element=Integer.parseInt(br.readLine());

st.push(element);

break;

case 2:

Integer obj=st.pop();

System.out.println("Popped= "+ obj);

break;

case 3:

System.out.println("Which element?");

element=Integer.parseInt(br.readLine());

position=st.search(element);

if(position == -1)

System.out.println("Element not found");

else

System.out.println("Position:" +position);

break;

default:

return;

}

System.out.println("stack contents: "+st);

}

}

}

Output:

Stack Operation

1 Push an element

2 Pop an element

3 Search an element?

4 Exist

1

Enter element:

52

stack contents: [52]

Stack Operation

1 Push an element

2 Pop an element

3 Search an element?

4 Exist

2 views0 comments

Recent Posts

See All
bottom of page