Worksheet 2.
Name: Khushwant Parihar UID: 18BCS1270
Section: 18_K2_IS_G3 Date: 03-04-2021
Subject: PBLJ LAB Subject Code: CSP-358
Aim/Overview of the practical:
Playing cards during travel is a fun filled experience. For this game they wanted
to collect all four unique symbols. Can you help these guys to collect unique
symbols from a set of cards?
Create Card class with attributes symbol and number. From our main method
collect each card details (symbol and number) from the user.
Collect all these cards in a set, since set is used to store unique values or objects.
Once we collect all four different symbols display the first occurrence of card
details in alphabetical order.
CODE:
import java.util.*;
class Card implements Comparable<Card> {
private char symbol;
private int number;
public Card() {}
public Card(char symbol, int number) {
super();
this.symbol = symbol;
this.number = number;
}
public char getSymbol() {
return symbol;
public void setSymbol(char symbol) {
this.symbol = symbol;
public int getNumber() {
return number;
public void setNumber(int number) {
this.number = number;
public String toString() {
return "Card [symbol=" + symbol + ", number=" + number + "]";
public int compareTo(Card o) {
if (this.symbol < o.symbol) return -1;
else if (this.symbol > o.symbol) return 1;
else return 1;
}
public int hashCode() {
return String.valueOf(symbol).hashCode();
public boolean equals(Object obj){
if (obj instanceof Card) {
Card card = (Card) obj;
return (card.symbol == this.symbol);
} else {
return false;
public class Exp22 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Set<Card> set = new HashSet<Card>();
for (int i = 0; i < 8; i++) {
System.out.println("Enter a card:");
Card card = new Card();
card.setSymbol(sc.nextLine().charAt(0));
card.setNumber(sc.nextInt());
sc.nextLine();
set.add(card);
System.out.println("Four symbols gathered in eight cards.");
System.out.println("Cards in Set are:");
for (Card card : set)
System.out.println(card.getSymbol() + " " +
card.getNumber()); sc.close();
OUTPUT:
Time complexity for this code is O(n)
Learning outcomes (What I have learnt):
1. Learn about sets of collection interface.
2. Learn about all the functions of sets