I have a custom MyArrayList that only stores int, float, or double values. I need to add user input to this array list. The input is stored as a string in a temporary variable, and I want to convert this string to the appropriate type before adding it to the list. How can I achieve this?
class MyArrayList<E> extends ArrayList<E>{
@Override
public boolean add(E e) {
if(e instanceof Integer || e instanceof Float || e instanceof Double) {
super.add(e);
return true;
} else {
throw new ClassCastException("Please enter Integer, Float or Double");
}
}
}
public class TestArrayList{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MyArrayList<Object> arraylist = new MyArrayList<>();
Object object = new Object();
try {
System.out.println("Enter Elements");
System.out.println("To stop input press '.'");
String temp;
while(scanner.hasNext()) {
temp = scanner.nextLine();
try {
object = temp;
} catch(Exception e) {}
if(temp.equals(".")) break;
else
arraylist.add(temp);
}
scanner.close();
System.out.println(arraylist.toString());
} catch(Exception e) {
System.out.println(e);
}
}
}
It's a bit odd requirement because you can only store Object
in your class and you have to use instanceof
when you get elements from a list. To convert the string a simple way is to try to convert and then catch but ignore any exception like this
public static Object convertToSomeNumber(String input) {
try {
return Integer.valueOf(input);
} catch (Exception e) {
}
try {
return Double.valueOf(input);
} catch (Exception e) {
}
return null;
}
Now you can use it on your temp
variable and add the result to the list if it is not null.
Note that I ignored Float so you need to add that yourself if you want to support it.