我正在从另一个自定义 Java 类的模式创建一个 StructType
,我可以从中提取列名和数据类型。
据我所知,似乎有两种构造 StructType 的方法:
我基本上可以使用这两种方法,因为我循环遍历我的自定义模式类以一个一个地提取字段。问题是,似乎 add
方法每次被调用时都会创建一个新的 StructType,这似乎是一种不必要的复杂处理方式,所以我实际上想知道它是否真的会创建 每次调用一个新对象。如果没有,我认为 add
是比创建新的 StructField
最佳答案
如果您查看 StructType 类的源代码,您会发现 add 方法调用了带有 new StructField
的 StructType
构造函数,因此它将创建新的 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());
}
}
关于java - 创建 Spark SQL 的 StructType : use add method or a constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40955038/