【发布时间】:2017-05-13 08:12:04
【问题描述】:
这是我要转换的 C# 代码
ArrayList.BinarySearch(Object, IComparer)
它的作用是将节点类对象与比较类对象进行比较,并返回 -1、0 或正整数。 我搜索了很多,并试图在 java 中转换它,但不能这样做。我需要一个方法、说明、库或任何可以帮助我实现它的东西。
类 Class1 {
[STAThread]
static void Main(string[] args)
{
ArrayList SolutionPathList = new ArrayList();
//Create a node containing the goal state node_goal
Node node_goal = new Node(null,null,1,15,15);
//Create a node containing the start state node_start
Node node_start = new Node(null,node_goal,1,0,0);
//Create OPEN and CLOSED list
SortedCostNodeList OPEN = new SortedCostNodeList ();
SortedCostNodeList CLOSED = new SortedCostNodeList ();
//Put node_start on the OPEN list
OPEN.push (node_start);
}
SortedNode 类是:
public class SortedCostNodeList
{
ArrayList _list;
NodeComparer _nodeComparer;
public SortedCostNodeList()
{
_list = new ArrayList ();
_nodeComparer = new NodeComparer ();
}
public int push (Node n)
{
int k = _list.BinarySearch (n,_nodeComparer);
if (k==-1) // no element
_list.Insert (0,n);
else if (k<0) // find location by complement
{
k=~k;
_list.Insert (k,n);
}
else if (k>=0)
_list.Insert (k,n);
return k;
}
和nodecomparer类是:
public class NodeComparer:IComparer
{
public NodeComparer()
{
}
public int Compare(object x, object y)
{
return ((Node)x).totalCost - ((Node) y).totalCost ;
}
}
我无法实现这段代码 //int k = _list.BinarySearch(n,_nodeComparer);
有什么帮助吗?
【问题讨论】:
-
BinarySearch方法完全按照它的建议行事:利用二分搜索算法来定位指定对象。你可以很容易地implement the method yourself,或者如果性能不是一个大问题,你总是可以使用常规的迭代搜索。 (请记住,二分查找仅对已排序的集合有效。) -
附带说明,我不知道您是否自己想出了这些 C# 方法,但您不应该再在 C# 中使用
ArrayList。它在很久以前就已经过时了,取而代之的是通用的List,在专门用于处理遗留系统的应用程序之外,它在各个方面都更可取。 (澄清一下,我说的是 C#。JavaArrayList很像 C#List,据我记得仍然可以很好地使用。)
标签: java c# android-studio