JAVA初学者在写Collections类的方法实验时发现一个关于二分法有趣的问题

MageXellos 2014-03-16 10:07:33
在看马士兵的视频自学JAVA,正好看到容器里的Collections,随手写了一个程序。
import java.util.*;

public class ListTest {
public static void main(String[] args) {
List l1 = new LinkedList();
l1.add("Pogba");
l1.add("Vidal");
l1.add("Pirlo");
l1.add("Marchiso");
System.out.println(l1);
Collections.sort(l1);
System.out.println(l1);
Collections.reverse(l1);
System.out.println(l1);
System.out.println(Collections.binarySearch(l1,"Vidal"));
}
}

结果发现输出结果是不正确,最后二分法查找输出的结果是-5,想了半天想不通。
然后看了下API文档,发现关于binarySearch里有这样一句话"The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined."意为使用二分法必须升序排列,否则结果不确定。
尝试注掉逆序,输出结果正确。
是不是JAVA里封装好的二分法查找只能找升序排列的,不能找降序的呢,还是降序的二分法查找有别的方法可以调用呢?
...全文
129 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
-江沐风- 2014-03-16
  • 打赏
  • 举报
回复
对于Java中是如何实现的,别人说的再多,终究是别人的,自己看一下源代码,你就知道了。
-江沐风- 2014-03-16
  • 打赏
  • 举报
回复
1楼怎么会有这些没用的信息啊!
rockets311 2014-03-16
  • 打赏
  • 举报
回复
可以加一个比较器参数
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class ListTest
{
	public static void main(String[] args)
	{
		List<String> l1 = new LinkedList<String>();
		l1.add("Pogba");
		l1.add("Vidal");
		l1.add("Pirlo");
		l1.add("Marchiso");
		System.out.println(l1);
		Collections.sort(l1);
		System.out.println(l1);
		Collections.reverse(l1);
		System.out.println(l1);
		
		System.out.println(Collections.binarySearch(l1, "Pirlo",
				new Comparator<String>()
				{
					@Override
					public int compare(String arg0, String arg1)
					{
						return arg1.compareTo(arg0);
					}
				}));
	}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧