
Computer Networking: A Top-Down Approach (7th Edition)
7th Edition
ISBN: 9780133594140
Author: James Kurose, Keith Ross
Publisher: PEARSON
expand_more
expand_more
format_list_bulleted
Question
Data structure & Algorithum java
1) Add a constructor to the class "AList" that creates a list from a given array of objects.
2) Add a method "getPosition" to the "AList" class that returns the position of a given object in the list. The header of the method is as follows : public int getPosition(T anObject)
3) Write a program that thoroughly tests all the methods in the class "AList".
4) Include comments to all source code.
![Here's a transcription of the image:
```java
import chapter5.ListInterface.*;
public class AList<T> implements ListInterface<T> {
private T[] list;
private int numberOfEntries;
private boolean integrityOK = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 1000;
public AList() throws Exception {
this(DEFAULT_CAPACITY);
}
public AList(int initialCapacity) throws Exception {
integrityOK = false;
// is capacity too small?
if (initialCapacity < DEFAULT_CAPACITY)
initialCapacity = DEFAULT_CAPACITY;
else
checkCapacity(initialCapacity);
T[] tempList = (T[]) new Object[initialCapacity + 1];
list = tempList;
numberOfEntries = 0;
integrityOK = true;
}
private void checkCapacity(int capacity) throws Exception {
if (capacity > MAX_CAPACITY)
throw new Exception("Attempt to create a list whose capacity exceeds the max.");
}
@Override
public void add(T newEntry) {
add(numberOfEntries + 1, newEntry);
}
@Override
public void add(int newPosition, T newEntry) {
try {
checkIntegrity();
if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) {
if (newPosition <= numberOfEntries + 1) {
makeRoom(newPosition);
list[newPosition] = newEntry;
numberOfEntries++;
ensureCapacity();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void checkIntegrity() {
// Implementation not shown
}
private void makeRoom(int newPosition) {
// Implementation not shown
}
private void ensureCapacity() {
// Implementation not shown
}
}
```
### Overview
This code defines a Java class called `AList` that implements the `ListInterface` interface. The class is designed to manage a list that can dynamically grow as new elements are added. It includes key attributes and methods:
1. **Attributes**:
- `list`: An array to store the entries.
- `numberOfEntries`: An integer tracking the number of entries in the list.
- `integrityOK`: A boolean indicating whether](https://content.bartleby.com/qna-images/question/dad5a646-4583-4c4b-beba-29e57d936914/5368ca6d-ccb5-40bd-bb12-92101512392a/pb8czqc_thumbnail.jpeg)
Transcribed Image Text:Here's a transcription of the image:
```java
import chapter5.ListInterface.*;
public class AList<T> implements ListInterface<T> {
private T[] list;
private int numberOfEntries;
private boolean integrityOK = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 1000;
public AList() throws Exception {
this(DEFAULT_CAPACITY);
}
public AList(int initialCapacity) throws Exception {
integrityOK = false;
// is capacity too small?
if (initialCapacity < DEFAULT_CAPACITY)
initialCapacity = DEFAULT_CAPACITY;
else
checkCapacity(initialCapacity);
T[] tempList = (T[]) new Object[initialCapacity + 1];
list = tempList;
numberOfEntries = 0;
integrityOK = true;
}
private void checkCapacity(int capacity) throws Exception {
if (capacity > MAX_CAPACITY)
throw new Exception("Attempt to create a list whose capacity exceeds the max.");
}
@Override
public void add(T newEntry) {
add(numberOfEntries + 1, newEntry);
}
@Override
public void add(int newPosition, T newEntry) {
try {
checkIntegrity();
if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) {
if (newPosition <= numberOfEntries + 1) {
makeRoom(newPosition);
list[newPosition] = newEntry;
numberOfEntries++;
ensureCapacity();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void checkIntegrity() {
// Implementation not shown
}
private void makeRoom(int newPosition) {
// Implementation not shown
}
private void ensureCapacity() {
// Implementation not shown
}
}
```
### Overview
This code defines a Java class called `AList` that implements the `ListInterface` interface. The class is designed to manage a list that can dynamically grow as new elements are added. It includes key attributes and methods:
1. **Attributes**:
- `list`: An array to store the entries.
- `numberOfEntries`: An integer tracking the number of entries in the list.
- `integrityOK`: A boolean indicating whether
![The image shows a section of Java code, likely part of a class handling an array-based list structure. Below is a transcription and explanation of the code:
```java
private void ensureCapacity() throws Exception {
int capacity = list.length - 1;
if (numberOfEntries >= capacity) {
int newCapacity = 2 * capacity;
checkCapacity(newCapacity);
list = Arrays.copyOf(list, newCapacity + 1);
}
}
private void makeRoom(int newPosition) {
int newIndex = newPosition;
int lastIndex = numberOfEntries;
for (int index = lastIndex; index >= newIndex; index--) {
list[index + 1] = list[index];
}
}
private void checkIntegrity() throws Exception {
if (!integrityOK)
throw new Exception("AList object is corrupt.");
}
@Override
public T remove(int givenPosition) {
// TODO Auto-generated method stub
return null;
}
@Override
public void clear() {
// TODO Auto-generated method stub
}
@Override
public T replace(int givenPosition, T newEntry) {
// TODO Auto-generated method stub
return null;
}
@Override
public T getEntry(int givenPosition) {
// TODO Auto-generated method stub
return null;
}
@Override
public T[] toArray() {
try {
checkIntegrity();
T[] result = (T[]) new Object[numberOfEntries + 1];
for (int index = 0; index < numberOfEntries; index++)
result[index] = list[index + 1];
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
```
### Explanation:
1. **ensureCapacity()**: Ensures the array backing the list has sufficient capacity. If not, it doubles the capacity and copies the existing elements into a new array with the increased size.
2. **makeRoom()**: Shifts elements to make space for a new entry at the specified position. It starts from the end (lastIndex) and shifts each element one position to the right up to newIndex.
3. **checkIntegrity()**: Checks if the list is in a valid state before performing operations; throws an exception if the list is corrupt.
4. **remove, clear, replace, getEntry**: These method signatures are present, but their implementations are](https://content.bartleby.com/qna-images/question/dad5a646-4583-4c4b-beba-29e57d936914/5368ca6d-ccb5-40bd-bb12-92101512392a/47l508l_thumbnail.jpeg)
Transcribed Image Text:The image shows a section of Java code, likely part of a class handling an array-based list structure. Below is a transcription and explanation of the code:
```java
private void ensureCapacity() throws Exception {
int capacity = list.length - 1;
if (numberOfEntries >= capacity) {
int newCapacity = 2 * capacity;
checkCapacity(newCapacity);
list = Arrays.copyOf(list, newCapacity + 1);
}
}
private void makeRoom(int newPosition) {
int newIndex = newPosition;
int lastIndex = numberOfEntries;
for (int index = lastIndex; index >= newIndex; index--) {
list[index + 1] = list[index];
}
}
private void checkIntegrity() throws Exception {
if (!integrityOK)
throw new Exception("AList object is corrupt.");
}
@Override
public T remove(int givenPosition) {
// TODO Auto-generated method stub
return null;
}
@Override
public void clear() {
// TODO Auto-generated method stub
}
@Override
public T replace(int givenPosition, T newEntry) {
// TODO Auto-generated method stub
return null;
}
@Override
public T getEntry(int givenPosition) {
// TODO Auto-generated method stub
return null;
}
@Override
public T[] toArray() {
try {
checkIntegrity();
T[] result = (T[]) new Object[numberOfEntries + 1];
for (int index = 0; index < numberOfEntries; index++)
result[index] = list[index + 1];
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
```
### Explanation:
1. **ensureCapacity()**: Ensures the array backing the list has sufficient capacity. If not, it doubles the capacity and copies the existing elements into a new array with the increased size.
2. **makeRoom()**: Shifts elements to make space for a new entry at the specified position. It starts from the end (lastIndex) and shifts each element one position to the right up to newIndex.
3. **checkIntegrity()**: Checks if the list is in a valid state before performing operations; throws an exception if the list is corrupt.
4. **remove, clear, replace, getEntry**: These method signatures are present, but their implementations are
Expert Solution

This question has been solved!
Explore an expertly crafted, step-by-step solution for a thorough understanding of key concepts.
This is a popular solution
Trending nowThis is a popular solution!
Step by stepSolved in 5 steps with 4 images

Knowledge Booster
Similar questions
- using System; class Program { publicstaticvoid Main(string[] args) { int number = 1; while (number <= 88) { Console.WriteLine(number); number = number + 2; } int[] randNo = newint[88]; Random r = new Random(); int i=0; while (number <= 88) { randNo[i] = number; number+=1; i+=1; } for (i = 0; i < 3; i++) { Console.WriteLine("Random Numbers between 1 and 88 are " + randNo[r.Next(1, 88)]); } } } this code counts from 1-88 in odds and then selects three different random numbers. it keeps choosing 0 as a random number everytime. how can that be fixed?arrow_forward17. Phone Book ArrayList Write a class named PhoneBookEntry that has fields for a person's name and phone number. The class should have a constructor and appropriate accessor and mutator methods. Then write a program that creates at least five PhoneBookEntry objects and stores them in an ArrayList. Use a loop to display the contents of each object in the ArrayList.arrow_forwardpublic List<String> getLikes(String user) This will take a String representing a user (like “Mike”) and return a unique List containing all of the users that have liked the user “Mike.” public List<String> getLikedBy(String user) This will take a String representing a user (like “Tony”) and return a unique List containing each user that “Tony” has liked. create a Main to test your work. import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set; public class FacebookLikeManager { public List<String> facebookMap; private Set<String> likesSets; public FacebookLikeManager() { facebookMap = new ArrayList<>(); likesSets = new HashSet<>(Arrays.asList("Mike","Kristen","Bill","Sara")); } public void buildMap(String filePath) {…arrow_forward
- Given the previous Car class, the following members have been added for you: Private: string * parts; //string array of part names int num_parts; //number of parts Public: void setParts(int numpart, string newparts[]) //set the numparts and parts int getNumParts() string * getParts() string getPart(int index) //return the string in parts at index num Please implement the following for the Car class: Add the copy constructor. (deep copy!) Add the copy assignment operator. (deep copy!) Add the destructorarrow_forwardclass Artist{StringsArtist(const std::string& name="",int age=0):name_(name),age_(age){}std::string name()const {return name_;}void set_name(const std::string& name){name_=name;}int age()const {return age_;}void set_age(int age){age_=age;}virtual std::string perform(){return std::string("");}private:int age_;std::string name_;};class Singer : public Artist{public:Singer():Artist(){};Singer(const std::string& name,int age,int hits);int hits() const{return hits_;}void set_hits(int hit);std::string perform();int operator+(const Singer& rhs);int changeme(std::string name,int age,int hits);Singer combine(const Singer& rhs);private:int hits_=0;};int FindOldestandMostSuccess(std::vector<Singer> list); Task: Implement the function int Singer::changeme(std::string name,int age,int hits) : This function should check if the values passed by name, age and hits are different than those stored. And if this is the case it should change the values. This should be done by…arrow_forwardclass Artist{StringsArtist(const std::string& name="",int age=0):name_(name),age_(age){}std::string name()const {return name_;}void set_name(const std::string& name){name_=name;}int age()const {return age_;}void set_age(int age){age_=age;}virtual std::string perform(){return std::string("");}private:int age_;std::string name_;};class Singer : public Artist{public:Singer():Artist(){};Singer(const std::string& name,int age,int hits);int hits() const{return hits_;}void set_hits(int hit);std::string perform();int operator+(const Singer& rhs);int changeme(std::string name,int age,int hits);Singer combine(const Singer& rhs);private:int hits_=0;};int FindOldestandMostSuccess(std::vector<Singer> list); Implement the function Singer Singer::combine(const Singer& rhs):It should create a new Singer object, by calling the constructor with the following values: For name it should pass a combination of be the name of the calling object followed by a '+' and then…arrow_forward
- Fibonacci A fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. For example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on… For this, you will implement a class that takes a positive integer (n) and returns the number in the nth position in the sequence. Examples When n is 1, the returned value will be 0. When n is 4, the returned value will be 2. When n is 9, the returned value will be 21. come up with the formula and base cases Implementation Create a class Fibonacci with a public static method getValue. Create a Main class to test and run your Fibonacci class.arrow_forwardAg 1- Random Prime Generator Add a new method to the Primes class called genRandPrime. It should take as input two int values: 1owerBound and upperBound. It should return a random prime number in between TowerBound (inclusive) and upperBound (exclusive) values. Test the functionality inside the main method. Implementation steps: a) Start by adding the method header. Remember to start with public static keywords, then the return type, method name, formal parameter list in parenthesis, and open brace. The return type will be int. We will have two formal parameters, so separate those by a comma. b) Now, add the method body code that generates a random prime number in the specified range. The simplest way to do this is to just keep trying different random numbers in the range, until we get one that is a prime. So, generate a random int using: int randNum = lowerBound + gen.nextInt(upperBound); Then enter put a while loop that will keep going while randNum is not a prime number - you can…arrow_forwardIn C++ struct myGrades { string class; char grade; }; Declare myGrades as an array that can hold 5 sets of data and then set a class string in each position as follows: “Math” “Computers” “Science” “English” “History” and give each class a letter gradearrow_forward
- Ajva.arrow_forwardx = 3 + numbers[3]++; System.out.println(x); QUESTION 2: Class Rectangle has two data members, length (type of float) and width (type of float). The class Rectangle also has the following: //mutator methods void setlength (float len) } //B. length = len; H accessor methods float getLength() I return length; The following statement creates an array of Rectangle with size 2: Rectangle[] arrayRectangle= new Rectangle[2]; Is it correct if executing the following statements? What is the output? If it is not correct, write the correct one arrayRectangle. setLength (12.59); System.out.printin[rectangle Set.getLength()); arrayRectangle[1].setLength(4.15); System.out.println(arrayRectangle[1].getLength()): QUESTION 3: Use the following int array int[] numbers = { 42, 28, 36, 72, 17, 25, 81, 65, 23, 58} -Open file data.txt to write. to write the values of the array numbers to the file with the y numbers to get the valuesarrow_forward10. Lottery Application Write a Lottery class that simulates a lottery. The class should have an array of five integers named lotteryNumbers. The constructor should use the Random class (from the Java API) to generate a random number in the range of 0 through 9 for each element in the array. The class should also have a method that accepts an array of five integers that represent a per- son's lottery picks. The method is to compare the corresponding elements in the two arrays and return the number of digits that match. For example, the following shows the lotteryNumbers array and the user's array with sample numbers stored in each. There are two matching digits (elements 2 and 4). lotteryNumbers array: User's array: 7 4 4 2 1 3 7 3 In addition, the class should have a method that returns a copy of the lotteryNumbers array. Demonstrate the class in a program that asks the user to enter five numbers. The program should display the number of digits that match the randomly generated…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY

Computer Networking: A Top-Down Approach (7th Edi...
Computer Engineering
ISBN:9780133594140
Author:James Kurose, Keith Ross
Publisher:PEARSON

Computer Organization and Design MIPS Edition, Fi...
Computer Engineering
ISBN:9780124077263
Author:David A. Patterson, John L. Hennessy
Publisher:Elsevier Science

Network+ Guide to Networks (MindTap Course List)
Computer Engineering
ISBN:9781337569330
Author:Jill West, Tamara Dean, Jean Andrews
Publisher:Cengage Learning

Concepts of Database Management
Computer Engineering
ISBN:9781337093422
Author:Joy L. Starks, Philip J. Pratt, Mary Z. Last
Publisher:Cengage Learning

Prelude to Programming
Computer Engineering
ISBN:9780133750423
Author:VENIT, Stewart
Publisher:Pearson Education

Sc Business Data Communications and Networking, T...
Computer Engineering
ISBN:9781119368830
Author:FITZGERALD
Publisher:WILEY