英文:
Calling parameterized constructor of super class with different datatype in java?
问题
public class Square extends Polygon {
public Square(Double side1) {
super(Arrays.asList(side1)); // You can convert the Double to a List<Double> using Arrays.asList()
}
}
英文:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public abstract class Polygon {
private List<Double> sides;
public Polygon(List<Double> sides)
{
this.sides=sides;
}
public List<Double> getSides() {
return sides;
}
}
public class Square extends Polygon{
public Square(Double side1) {
// here i want to call super(sides). how do i convert double(side1) to list.
}
}
I want to call the constructor of polygon class from square class but how do i convert double to list?
Note: I cannot change any datatype.
答案1
得分: 3
你可以使用相同的 double 值重复四次来创建一个列表:
super(Arrays.asList(side1, side1, side1, side1)); // Java 8
super(List.of(side1, side1, side1, side1)); // Java 9+
英文:
You can create a list with that one double repeated four times:
super(Arrays.asList(side1, side1, side1, side1)); //java 8
super(List.of(side1, side1, side1, side1)); //java 9+
答案2
得分: 0
以下代码将把您的 double 值转换为一个列表,可以将其用作调用构造函数的参数。
DoubleStream.of(doublesArray).boxed().collect(Collectors.toCollection(ArrayList::new));
doublesArray 是 Double 参数。
英文:
The below code, will convert your double to a list, which can be used as a parameter to invoke the constructor.
DoubleStream.of(doublesArray).boxed().collect(Collectors.toCollection(ArrayList::new));
doublesArray is the Double param
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论