我正在从另一个自定义Java类的模式创建var StrawberryCough = require("inquirer");
var mainCharacter = 70;
var zombie = {
hp: 15,
num: 0
}
StrawberryCough.prompt([
{
type: "input",
message: "Random Number 1-5: ",
name: "number"
}
]).then(function(user){
parseInt(user.number);
var ranNum = Math.round(Math.random() * (5 - 1) + 1);
zombie.num = ranNum;
if(user.number === zombie.num)
{
var damage = Math.round(Math.random() * (5 - 1) + 1);
console.log("Character Damage: ", damage);
zombie.hp -= damage;
console.log("zombie hp", zombie.hp);
if(zombie.hp <= 0)
{
console.log("You win!")
return;
}
}
else if(user.number !== zombie.num)
{
var zomDamage = Math.round(Math.random() * (5 - 1) + 1);
console.log("Zombie Damage: ", zomDamage);
mainCharacter -= zomDamage;
console.log("main hp", mainCharacter);
if(mainCharacter <= 0)
{
console.log("You lose!");
return;
}
}
});
,我可以从中提取列名和数据类型。
据我所知,似乎有两种方法来构造StructType:
add
method 我基本上可以使用这两种方法,因为我遍历我的自定义模式类以逐个提取字段。问题是,似乎StructType
方法每次调用时都会创建一个新的StructType,这似乎是不必要的复杂处理方式,所以我实际上想知道它是否真的会创建每次调用一个新对象。如果没有,我认为add
比创建add
答案 0 :(得分:5)
如果检查StructType类的源代码,您将看到add方法使用StructType
调用new StructField
构造函数,因此它将创建新的StructType。
def add(name: String, dataType: DataType): StructType = {
StructType(fields :+ new StructField(name, dataType, nullable = true, Metadata.empty))
}
您可以使用以下示例程序验证它。
public class QuickTest {
public static void main(String[] args) {
SparkSession sparkSession = SparkSession
.builder()
.appName("QuickTest")
.master("local[*]")
.getOrCreate();
//StructType
StructType st1 = new StructType().add("name", DataTypes.StringType);
System.out.println("hashCode "+st1.hashCode());
System.out.println("structType "+st1.toString());
//add
st1.add("age", DataTypes.IntegerType);
System.out.println("hashCode "+st1.hashCode());
System.out.println("structType "+st1.toString());
//add and assign
StructType st2 = st1.add("age", DataTypes.IntegerType);
System.out.println("hashCode "+st2.hashCode());
System.out.println("structType "+st2.toString());
//constructor
StructType st3 = new StructType(new StructField[] {new StructField("name", DataTypes.StringType, true, null), new StructField("age", DataTypes.IntegerType, true, null)});
System.out.println("hashCode "+st3.hashCode());
System.out.println("structType "+st3.toString());
}
}