Create a class called ManyStructures. It encapsulates an instance variable that
ID: 3782418 • Letter: C
Question
Create a class called ManyStructures. It encapsulates an instance variable that is a long array. The length of the array should be dependent on an argument passed into a constructor. Include get and set methods so you can assign values to the elements of the array.
The ManyStructures class should also have the following methods.
getArray() -- which returns a copy of the instance variable array. Note that I said "copy"!
getQueue() -- which returns the data in the instance variable as a queue. The queue should have the functionality of the basic queue from your textbook.
getStack() -- which returns the data in the instance variable array as a stack. The stack should have the functionality of the basic stack from your textbook.
getLinkedList() -- which returns the data in the instance variable array as a linked list. The linked list should have the functionality of the basic linked list from your textbook. Note that in order to do this you will have to create something equivalent to the Link class from exercise 5A and embed the aray's long data within objects of that class.
Include a ManyStructuresDriver class that tests the ManyStructures class, its methods, and the data structures returned by the methods listed above
Explanation / Answer
Ques, LinkedList and Stack are all built in classes in Java
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Queue;
import java.util.Stack;
class ManyStructures
{
long[] arr;
ManyStructures(int s)
{
arr = new long[s];
}
void setArray()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter "+arr.length+" elements of array ");
for(int i=0; i<arr.length;i++)
{
arr[i]= sc.nextLong();
}
}
long[] getArray()
{
long[] copy = arr;
return copy;
}
LinkedList getLinkedList()
{
LinkedList<Long> list = new LinkedList<Long>();
for(int i=0; i<arr.length;i++)
{
list.add(arr[i]);
}
return list;
}
Queue getQueue()
{
Queue q = new LinkedList();
for(int i=0; i<arr.length;i++)
{
q.add(arr[i]);
}
return q;
}
Stack getStack()
{
Stack s = new Stack();
for(int i=0; i<arr.length;i++)
{
s.add(arr[i]);
}
return s;
}
}
public class ManyStructuresDriver {
public static void main(String[] args) {
ManyStructures ms= new ManyStructures(5);
ms.setArray();
long[] a= ms.getArray();
/*for(int i=0;i< a.length;i++)
System.out.println(a[i]+" ");
}*/
Queue q=ms.getQueue();
Stack s=ms.getStack();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.