对与 Java 中的字符串数组相关的 int 数组进行排序
我有两个数组:
int[] intArray = new int[]{point1,point2,point3,point4};
String[] strArray = new String[]{worda,wordb,wordc,wordd};
现在,我想按数字顺序对 intArray 进行排序,以便 strArray 遵循相同的顺序。我确信这是一个常见问题,但我无法让它发挥作用。我制作了一个 TreeMap 并添加了每个数组中的值。 TreeMap 不应该自动按键 intArray[] 排序吗?它似乎不起作用。
TreeMap theMap = new TreeMap();
theMap.put(intArray, strArray);
I have two arrays:
int[] intArray = new int[]{point1,point2,point3,point4};
String[] strArray = new String[]{worda,wordb,wordc,wordd};
Now, I want to sort intArray in numerical order, such that strArray follows the same order. I'm sure this is a common problem, but I can't get it to work. I made a TreeMap and added the values in from each array. Shouldn't a TreeMap automatically sort by the key, intArray[]? It doesn't appear to work.
TreeMap theMap = new TreeMap();
theMap.put(intArray, strArray);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您对 TreeMap 的使用方式感到困惑。
TreeMap
保持键的排序。在你的情况下,你有一个键 -intArray
所以没有什么可以排序的。您必须将每一对放入映射中:对于每个可能的i
,theMap.put(intArray[i], strArray[i])
。顺便说一句,如果只是为了排序,则不需要强制性的
TreeMap
。您可以创建一个包装点和字符串的类的列表,然后使用Collections.sort(list)
对其进行排序。当然你必须实现Comparable
接口。You are confusing how a
TreeMap
is used.TreeMap
keeps the keys sorted. In your case you have one key -intArray
so there is nothing to be sorted. You have to put every pair into the map:theMap.put(intArray[i], strArray[i])
for every possiblei
.By the way, if it is only for the sorting you don't need obligatory a
TreeMap
. You can make a list of a class which wraps a point and a string and then sort it withCollections.sort(list)
. Of course you have to implementComparable
interface.是的,TreeMap 应该可以正常工作。但是,不要添加两个数组,而是添加每对值。
Yes a TreeMap should work fine. However instead of adding both arrays add the each pair of values.