Reputation: 207
I apologize in advance if I am making any mistakes asking this question. I am new to stackoverflow and java.
My problem is that I want to be able to convert an ordinary array of doubles to an arraylist, I need to operate on this arraylist element wise to change values from x to -x (using an interface)
I am trying to just get array doubles to convert to an arraylist using a for loop element by element first (thought I should get is working first) but the .add does not seem to work which is the solution that seems to appear when I research it. currently it saying "cannot instantiate the type Num" I've tried removing abstract still no good.
Am I going about this completely wrong? Thanks for help in advance.
Here are my codes.
public interface Num {
public void neg(); // negation
public void sqrt(); // square root
public String asString(); // number represented as a string
}
public class NumDouble implements Num {
Double d;
public NumDouble(Double d) {
this.d = d;
}
@Override
public void neg() {
d = -d;
}
@Override
public void sqrt() {
d = Math.sqrt(d);
}
@Override
public String asString() {
return d.toString();
}
}
THIS IS THE CODE I HAVE BEEN TRYING
import java.util.ArrayList;
import java.util.Arrays;
public abstract class NumList implements Num {
ArrayList<Num> nums = new ArrayList<Num>();
double[] doubles = {2.3, 2.2, 2.4};
public void neg() {
for (int i = 0; i < doubles.length; i++) {
double value = doubles[i];
nums.add(new Num(value)); <------this is highlighting as an error
}
return;
}
public void sqrt() {
}
}
Upvotes: 2
Views: 626
Reputation: 30528
You can either use NumDouble
to do so or create an anonymous instance of Num
.
The latter would look like something like this:
Num num = new Num() {
Double d;
@Override
public void neg() {
d = -d;
}
@Override
public void sqrt() {
d = Math.sqrt(d);
}
@Override
public String asString() {
return d.toString();
}
};
As you can see this does not make sense since you can't add constructors to an anonymous instance and your interface does not contain a setter.
Just a note: NumList
is not really a Num
since it does not fit in the Num
abstraction you create.
So my suggestion is to either use NumDouble
like this:
nums.add(new NumDouble(value));
or create a new class extending Num
.
Upvotes: 1