微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java的NavigableMap.floorEntry的C Sharp中的等价物,ceilingEntry

我在 Java中多次使用NavigableMap接口,这很方便.

具体来说,我喜欢使用它的floorEntry和ceilingEntry方法,它们分别为您提供下一个最低或最高的地图条目.

我试图在C#中找到它们的等价物,但我很简短.以下是我想要获得的一个例子.

我看过C#SortedDictionary和扩展方法,虽然它看起来像是在球场,但我还没找到我正在寻找的东西.

谢谢!
大号

package com.lewis.needsanavigablemapincsharp;

import java.util.NavigableMap;
import java.util.TreeMap;

public class Main {

    public static void main(String[] args) {

        NavigableMap<Float,String> neededMap = new TreeMap<Float,String>();

        neededMap.put(1.0f,"first!");
        neededMap.put(3.0f,"second!");

        System.out.println("see how useful this is? (looking up indices that aren't in my map)");
        System.out.println(neededMap.floorEntry(2.0f));
        System.out.println(neededMap.ceilingEntry(2.0f));

    }
}

输出是:

see how useful this is? (looking up indices that aren’t in my map)
1.0=first!
3.0=second!

解决方法

遗憾的是,该解决方案要求您编写自定义扩展.所以,我已经完成了它,并将其作为一个要点上传SortedDictionaryExtensions.cs.

它通过将字典的密钥集合转换为列表来利用List< T> .BinarySearch方法.然后,在答案here的帮助下,我们确定密钥是否存在,如果不存在,我们将楼层和天花板值作为按位补码,然后选择我们需要的方法.

请注意我没有测试过这种算法的效率,但乍一看似乎还不错.

你可以像这样测试它:

SortedDictionary<float,string> neededMap = new SortedDictionary<float,string>();

neededMap.Add(1.0f,"first!");
neededMap.Add(3.0f,"second!");

Console.WriteLine("see how useful this is? (looking up indices that aren't in my map)");
Console.WriteLine(neededMap.FloorEntry(2.0f));
Console.WriteLine(neededMap.CeilingEntry(2.0f));

原文地址:https://www.jb51.cc/java/129435.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐