如何在Vala中获取Gee.SortedMap的首个键(最小键)?
在Vala中获取Gee.SortedMap的第一个键
Gee.SortedMap本身没有直接提供类似Java firstKey()的方法,但它继承自Gee.NavigableMap接口,这个接口包含的first_key()方法可以用来获取排序后的第一个(最小的)键。
需要注意的是,调用first_key()前必须确保集合不为空,否则会抛出异常。以下是两种可行的实现方式:
方式一:强制转换为NavigableMap
如果变量声明为Gee.SortedMap,可以通过强制转换调用目标方法:
Gee.SortedMap<int, string> foo = new Gee.TreeMap<int, string> (); // 添加测试数据 foo.set(3, "three"); foo.set(1, "one"); foo.set(2, "two"); if (!foo.is_empty) { int first_key = ((Gee.NavigableMap<int, string>) foo).first_key(); print("最小的键是: %d\n", first_key); // 输出 1 } else { print("集合为空,无法获取键\n"); }
方式二:直接声明为NavigableMap
由于Gee.TreeMap本身实现了NavigableMap接口,你可以直接将变量声明为该类型,省去强制转换步骤:
Gee.NavigableMap<int, string> foo = new Gee.TreeMap<int, string> (); foo.set(3, "three"); foo.set(1, "one"); foo.set(2, "two"); if (!foo.is_empty) { int first_key = foo.first_key(); print("最小的键是: %d\n", first_key); }
两种方式都能实现需求,选择哪种取决于你的代码结构和变量声明习惯。
内容的提问来源于stack exchange,提问作者Wayne
相关产品推荐
相关产品推荐

