0% found this document useful (0 votes)
12 views8 pages

Java Collection Assignment Solutions

The document consists of a Java assignment divided into two parts. Part A includes creating a game package with classes for players, comparing scores, and handling user input, while Part B covers various tasks involving data structures like LinkedList and Vector, including student records and book management. Each task is accompanied by code solutions demonstrating the required functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views8 pages

Java Collection Assignment Solutions

The document consists of a Java assignment divided into two parts. Part A includes creating a game package with classes for players, comparing scores, and handling user input, while Part B covers various tasks involving data structures like LinkedList and Vector, including student records and book management. Each task is accompanied by code solutions demonstrating the required functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA ASSIGNMENT(COLLECTION)

--------------------------------Part A --------------------------------------------------

Q1. Create Package game.

Q2. Design abstract class Player having data members like name, mobile no and score.

Q3. Define abstract method play that return integer. i.e. score of players.

Q4. Define no argument and parameterized constructor.

Q5. Design class player 1 and player 2 that inherits player class.

Q6. Override base class method.

Q7. Define both constructor no argument and parameterized in both classes.

Q8. Create class Final Result that contains main method.

Q9. Ask details of two player from user in main.

Q10. Call parameterized constructor of both classes to initialize value of class variables.

Q11. Create Compare score method

String compare Score (Player1 p, Player2 p2). Compare score using play method of both
classes.
Q12. Above method return which player has maximum score if player1 has maximum score
it will return “Player1” else return “player2”.
Q13. In main check display details of player who has won the game.

SOLUTION: package Collection;


import [Link];
public class quest1 {

abstract static class Player {


String name;
String mobileno;
int score;
public Player(String name, String mobileno, int score) {
[Link] = name;
[Link] = mobileno;
[Link] = score;
}
abstract int play();
}
static class Player1 extends Player {
public Player1(String name, String mobileno, int score) {
super(name, mobileno, score);
}
@Override
int play() {
return score;
}
}
static class Player2 extends Player {
public Player2(String name, String mobileno, int score) {
super(name, mobileno, score);
}
@Override
int play() {
return score;
}
}
public static String compareScore(Player p1, Player p2) {
return [Link]() > [Link]() ? "Player1" : "Player2";
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter details for Player1:");
[Link]("Name: ");
String name1 = [Link]();
[Link]("Mobile No: ");
String mobileno1 = [Link]();
[Link]("Score: ");
int score1 = [Link]();
[Link](); // Consume newline character
[Link]("Enter details for Player2:");
[Link]("Name: ");
String name2 = [Link]();
[Link]("Mobile No: ");
String mobileno2 = [Link]();
[Link]("Score: ");
int score2 = [Link]();
Player1 player1 = new Player1(name1, mobileno1, score1);
Player2 player2 = new Player2(name2, mobileno2, score2);
String winner = compareScore(player1, player2);
[Link]("Winner is: " + winner);
}
}
------------------------------------------Part B---------------------------------------------

Q1. Write a program that ask student name, roll no and marks from user. Initialize value of
class using constructor. Define to string method in class create Student main class to call all
class function. Ask 5 record from user and store then in LinkedList and display all data.

SOL: package Collection;

import [Link];

import [Link];

public class partBQ1 {

static class Student {

String name;

int rollNo;

double marks;

public Student(String name, int rollNo, double marks) {

[Link] = name;

[Link] = rollNo;

[Link] = marks;

public String toString() {

return "Student [Name: " + name + ", Roll No: " + rollNo + ", Marks: " + marks + "]";

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

LinkedList<Student> students = new LinkedList<>();

for (int i = 0; i < 5; i++) {

[Link]("Enter details for student " + (i + 1) + ":");

[Link]("Enter name: ");


String name = [Link]();

[Link]("Enter roll number: ");

int rollNo = [Link]();

[Link]("Enter marks: ");

double marks = [Link]();

[Link]();

Student student = new Student(name, rollNo, marks);

[Link](student);

[Link]("\nAll student records:");

for (Student student : students) {

[Link](student);

[Link]();

OUTPUT: Enter details for student 1:

Enter name: VIRAT

Enter roll number: 5

Enter marks: 79

Enter details for student 2:

Enter name: ROHIT

Enter roll number: 4

Enter marks: 80

Enter details for student 3:

Enter name: MAHENDRA

Enter roll number: 3

Enter marks: 95
Enter details for student 4:

Enter name: SHIKHAR

Enter roll number: 2

Enter marks: 66

Enter details for student 5:

Enter name: DINESH

Enter roll number: 1

Enter marks: 60

All student records:

Student [Name: VIRAT, Roll No: 5, Marks: 79.0]

Student [Name: ROHIT, Roll No: 4, Marks: 80.0]

Student [Name: MAHENDRA, Roll No: 3, Marks: 95.0]

Student [Name: SHIKHAR, Roll No: 2, Marks: 66.0]

Student [Name: DINESH, Roll No: 1, Marks: 60.0]

Q2. Write a program to create vector of string and add elements to vector check vector
class main functions like 1)adding elements in vector 2)traversing all vector elements 3)print
vector object hash code 4)get particular element value using get function 5)print size and
capacity of vector 6)add null data in vector 7)print index value of null elements hint
[Link](null) 8)add element at particular position hint [Link]("",5); 9)remove
particular element from vector.

SOL: package Collection;


import [Link];

public class partBQ2 {


public static void main(String[] args) {
Vector<String> v = new Vector<String>();

[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

for (String s : v) {
[Link](s);
}
[Link]("HashCode: " + [Link]());
[Link]("Element at index 1: " + [Link](1));
[Link]("Size: " + [Link]());
[Link]("Capacity: " + [Link]());

[Link](null);
[Link]("Index of null: " + [Link](null));

[Link]("Mango", 1);
[Link]("After inserting Mango at index 1: " + v);

[Link]("Banana");
[Link]("After removing Banana: " + v);
}
}
OUTPUT: Apple

Banana

Cherry

HashCode: -78891027

Element at index 1: Banana

Size: 3

Capacity: 10

Index of null: 3

After inserting Mango at index 1: [Apple, Mango, Banana, Cherry, null]

After removing Banana: [Apple, Mango, Cherry, null]

Q3. Write program for maintaining book record of library. Use ArrayList Class to hold an
multiple book record and display all book record using iterator. b) traverse arraylist and store
each book record in class object and display book name.

SOL: package Collection;


import [Link];
import [Link];

public class partBQ3 {


public static void main(String[] args) {
class Book {
int id;
String name;
String author;

Book(int id, String name, String author) {


[Link] = id;
[Link] = name;
[Link] = author;
}
public String toString() {
return id + " " + name + " " + author;
}
}
ArrayList<Book> list = new ArrayList<Book>();
[Link](new Book(101, "Java", "James"));
[Link](new Book(102, "Python", "Guido"));
[Link](new Book(103, "C++", "Bjarne"));
Iterator<Book> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}

for (Book b : list) {


[Link]("Book Name: " + [Link]);
}
}
}

OUTPUT: 101 Java James

102 Python Guido

103 C++ Bjarne

Book Name: Java

Book Name: Python

Book Name: C++

Q4. Write a Java program to create a new tree set, add some colours (string) and print out
the tree set.

SOL: package Collection;


import [Link];

public class partBQ4 {


public static void main(String[] args) {
TreeSet<String> colors = new TreeSet<String>();
[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("Yellow");

[Link](colors);
}
}

OUTPUT: [Blue, Green, Red, Yellow]

Q5. Write a Java program to compare two linked lists.


SOL: package Collection;
import [Link];

public class partBQ5 {


public static void main(String[] args) {
LinkedList<String> list1 = new LinkedList<String>();
LinkedList<String> list2 = new LinkedList<String>();

[Link]("A");
[Link]("B");
[Link]("C");

[Link]("A");
[Link]("B");
[Link]("C");

boolean isEqual = [Link](list2);


[Link]("Are LinkedLists equal? " + isEqual);
}
}

OUTPUT: Are Linked Lists equal? true

Q6. Write a java program to compare two hash Set.

SOL: package Collection;


import [Link];

public class partBQ6 {


public static void main(String[] args) {
HashSet<String> set1 = new HashSet<String>();
HashSet<String> set2 = new HashSet<String>();

[Link]("One");
[Link]("Two");
[Link]("Three");

[Link]("One");
[Link]("Two");
[Link]("Three");

boolean isEqual = [Link](set2);


[Link]("Are HashSets equal? " + isEqual);
}
}

OUTPUT: Are Hash Sets equal? true

Common questions

Powered by AI

The encapsulation practices observed involve declaring class variables like name, mobileno, and score as private and using constructors to initialize them. This restricts direct access to these variables from outside the class, ensuring that any modifications or accesses go through controlled mechanisms (methods or constructors), which preserves the integrity of the data and enhances security. It is important because it allows the developer to change internal implementation without affecting how external code interacts with it .

The Java solutions handle user input effectively by utilizing the Scanner class to collect data from the console, ensuring that the input type matches the expected data type for processing. Data storage is managed through the use of collection classes like LinkedList and Vector, which provide dynamic storage and retrieval capabilities. This allows for flexible handling of user data without concerns of fixed size limitations, ensuring that applications can manage variable amounts of input data efficiently .

The method used to compare LinkedLists and HashSets in the examples is the equals() method, which checks for the equality of elements within the collections. The limitation of this approach is that it relies on the assumption that the collections contain the same elements in the same order (for lists) or with the same entries (for sets). It does not account for differences in duplicates and does not handle custom comparison logic beyond what's defined in the objects' equals methods themselves .

Polymorphism in the described Java Player class system manifests through the overridden play method in Player1 and Player2 classes. When the play method is called on a Player reference holding either a Player1 or Player2 object, the overridden method of the instance type is executed. This dynamic method dispatch is central to polymorphism, allowing a single interface (the play method in the Player class) to be used for different underlying forms (implementations in Player1 and Player2).

The implementation of the Student class and its storage in a linked list conforms to object-oriented principles by encapsulating student data within a class and utilizing constructors to manage state. The use of a LinkedList to hold multiple Student objects demonstrates the principle of composition, as the list is composed of independent Student objects. Additionally, by using methods like toString(), it ensures that interactions with Student are abstracted from the underlying data representation, promoting data hiding and separation of concerns .

Creating a package in Java, such as the 'game' package in this context, serves the purpose of organizing classes and interfaces into a namespace, which helps in avoiding naming conflicts and can also control access with protected and default access levels. This organization also makes it easier to maintain and understand the codebase as it grows in complexity and size .

The solution demonstrates the dynamic nature of vectors by showing how vectors can automatically increase their capacity to accommodate more elements beyond their initial size. It highlights operations such as adding elements, nulls, inserting elements at specific positions, and removing elements, which showcase vectors' ability to resize and manage memory efficiently as needed, unlike arrays with a fixed size .

The use of TreeSet in the given example is significant because it maintains sorted order of elements, which is ideal for storing data that needs to be accessed in a sorted manner. Unlike HashSet or LinkedHashSet, TreeSet uses a Red-Black tree structure to keep the elements ordered as they are inserted. This property can enhance data retrieval for sorted elements but comes at a cost of generally slower performance for add, remove, and contains operations compared to HashSet due to maintaining tree balance .

Using an abstract class like Player provides the advantage of having shared code and implementation details across subclasses, allowing them to inherit these features, such as the fields and constructor. This can reduce code duplication and is useful when there are base implementations. However, the disadvantage is that Java only supports single inheritance, limiting the ability to extend multiple abstract classes. In contrast, using an interface would allow for implementing multiple behaviors across unrelated classes but would require all methods to be fully implemented by each class, leading to potential code duplication if the same base logic were needed across different implementations .

The Java solution for managing library book records utilizes the Iterator interface to traverse through an ArrayList of Book objects. The use of Iterator allows the program to iterate over the list and retrieve each book's details sequentially. This method is advantageous as it provides a standard way to iterate over collections and avoid potential issues with data modification during iteration, enhancing robustness and maintainability .

You might also like