调用Java中具有不同数据类型的超类的参数化构造函数?

huangapple go评论91阅读模式
英文:

Calling parameterized constructor of super class with different datatype in java?

问题

  1. public class Square extends Polygon {
  2. public Square(Double side1) {
  3. super(Arrays.asList(side1)); // You can convert the Double to a List<Double> using Arrays.asList()
  4. }
  5. }
英文:
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Arrays;
  4. public abstract class Polygon {
  5. private List&lt;Double&gt; sides;
  6. public Polygon(List&lt;Double&gt; sides)
  7. {
  8. this.sides=sides;
  9. }
  10. public List&lt;Double&gt; getSides() {
  11. return sides;
  12. }
  13. }
  14. public class Square extends Polygon{
  15. public Square(Double side1) {
  16. // here i want to call super(sides). how do i convert double(side1) to list.
  17. }
  18. }

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 值重复四次来创建一个列表:

  1. super(Arrays.asList(side1, side1, side1, side1)); // Java 8
  2. super(List.of(side1, side1, side1, side1)); // Java 9+
英文:

You can create a list with that one double repeated four times:

  1. super(Arrays.asList(side1, side1, side1, side1)); //java 8
  2. super(List.of(side1, side1, side1, side1)); //java 9+

答案2

得分: 0

以下代码将把您的 double 值转换为一个列表,可以将其用作调用构造函数的参数。

  1. 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.

  1. DoubleStream.of(doublesArray).boxed().collect(Collectors.toCollection(ArrayList::new));

doublesArray is the Double param

huangapple
  • 本文由 发表于 2020年8月10日 22:40:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63342407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定