GraphX中如何声明空Edge类型数组替代含dummy数据的数组
Great question—ditching that dummy edge is straightforward once you explicitly define the array's type so Scala knows what kind of elements it should hold. Here's how to adjust your code:
Step 1: Declare an Empty Typed Array
Replace your dummy array initialization with one of these options to create an empty array of Edge type:
// Option 1: Explicit type annotation + empty array var edgeArray: Array[Edge] = Array.empty[Edge] // Option 2: Shorter syntax (Scala infers the type automatically) var edgeArray = Array.empty[Edge] // Option 3: Alternative empty array syntax var edgeArray = Array[Edge]()
All three create an empty array ready to hold Edge instances—no dummy data required.
Step 2: Keep Appending Edges as Before
Your existing code to append edges will work exactly as it did before, since the array is now correctly typed:
edgeArray = edgeArray ++ Array(Edge(VertexId, VertexId, edgeProperty("", "")))
A Quick Performance Tip
If you’re planning to add a lot of edges, using Array can be inefficient because every ++ operation creates a new array under the hood. For better performance, consider using ArrayBuffer (a mutable collection) instead, then convert it to an Array once you’re done adding edges:
import scala.collection.mutable.ArrayBuffer var edgeBuffer = ArrayBuffer.empty[Edge] edgeBuffer += Edge(VertexId, VertexId, edgeProperty("", "")) // Add as many edges as needed... // Convert to Array when ready val edgeArray = edgeBuffer.toArray
This avoids the overhead of creating new arrays with each append.
内容的提问来源于stack exchange,提问作者Nargis

