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

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

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&lt;Double&gt; sides;
	
	public Polygon(List&lt;Double&gt; sides)
	{
		this.sides=sides;
	}

	public List&lt;Double&gt; 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

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:

确定