Note that this class supports an extremely robust method called map, which takes
ID: 3599473 • Letter: N
Question
Note that this class supports an extremely robust method called map, which takes an interface as an argument. If you look at the function header to ma below, you’ll see that aclassthatimplementsWeirdList.mapsuppliesonlyasinglemethodint apply(int x). So, add the following map method to WeirdList.
/ Apply FUNC.apply to every element of THIS WeirdList in
sequence , and return a WeirdList of the resulting values . /
public WeirdList map( IntUnaryFunction func ) { // REPLACE LINE BELOW WITH THE RIGHT ANSWER.
return null ; }
Finally, implement add for WeirdListClient below.
// Functions to increment and sum the elements of a WeirdList
class WeirdListClient {
// Returns the result of adding N to each element of L. static WeirdList add(WeirdList L, int n) {
return null ; // REPLACE THIS LINE WITH THE RIGHT ANSWER .
}
// Returns the sum of the elements in L
static int sum( WeirdList L) {
return 0; // REPLACE THIS LINE WITH THE RIGHT ANSWER.
} }
Explanation / Answer
public class WeirdList
{
//declare start variable of type int and end of type WeirdList for adding elements in sequence to the list
// declare constructor for initializing start and end
private int start;
private WeirdList end;
public WeirdList(int s,WeirdList e)
{
start=s;
end=e;
}
public WeirdList map(IntUnaryFunction func)
{
return new WeirdList(func.apply(start),end.map(func));
}
}
// now create user defined class AddDetails that implements IntUnaryFunction interface
public class AddDetails
{
private int a;
private int sum;//gets the sum of elements in list
public AddDetails()
{
sum=0;
}
// constructor for initializing a value in order to add the elements in sequence
public AddDetails(int x)
{
a=x;
}
// providing body for apply() from intunaryfunction interface
public int apply(int x)
{
return a+x;
}
public int getSum()
{
return sum;
}
}
class WeirdListClient
{
static WeirdList add(WeirdList L,int n)
{
AddDetails func=new AddDetails(n);
return L.map(func);
}
static int sum(WeirdList L)
{
AddDetails func=new AddDetails();
L.map(func);
return func.getSum();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.