In java please! as soon as pssble, should be simple code :) thank you! Complete
ID: 3811676 • Letter: I
Question
In java please! as soon as pssble, should be simple code :) thank you!
Complete a generic class with the prototype below.
public class Choices<T>{
// a class that represents either None or Some of a type. Add a private field as needed. (None indicates the absence of an item, some indicates the presence of a single item)
public Choices();
//construct a Choice which has a None of a type
public Choices (T item);
//construct a Choice which has Some which is the argument item
public boolean hasSome();
//returns true if the Choices has Some and false if it has None
public T getSome();
//if the Choices has Some, return the item it was constructed with. If the Choices has None, thrown a runtime exception with the message " Choices has None "
public String toString();
// if the Choices has Some, return a string formated "Some(XXX)" where XXX is repalced by the toString() of the item. If the Choices has None, return the string "None".
Explanation / Answer
PROGRAM CODE:
package array;
public class Choices<T>{
T data;
// a class that represents either None or Some of a type. Add a private field as needed. (None indicates the absence of an item, some indicates the presence of a single item)
public Choices()
{
data = null;
}
//construct a Choice which has a None of a type
public Choices (T item)
{
data = item;
}
//construct a Choice which has Some which is the argument item
public boolean hasSome()
{
if(data == null)
return false;
else return true;
}
//returns true if the Choices has Some and false if it has None
public T getSome()
{
if(data == null)
throw new RuntimeException(" Choices has None ");
else
return data;
}
//if the Choices has Some, return the item it was constructed with. If the Choices has None, thrown a runtime exception with the message " Choices has None "
public String toString()
{
if(data == null)
return "None";
else return "Some(" + data.toString() + ")";
}
// if the Choices has Some, return a string formated "Some(XXX)" where XXX is repalced by the toString() of the item. If the Choices has None, return the string "None".
//comment this code if not needed
public static void main(String args[])
{
Choices<Integer> intChoice = new Choices<>();
System.out.println("Expected: None" + " " + "Actual: " + intChoice);
Choices<String> stringChoice = new Choices<String>("Hello World");
System.out.println("Expected: Hello World" + " " + "Actual: " + stringChoice.getSome());
}
}
OUTPUT:
Expected: None
Actual: None
Expected: Hello World
Actual: Hello World
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.