对与 Java 中的字符串数组相关的 int 数组进行排序

发布于 2024-10-10 04:53:31 字数 409 浏览 0 评论 0原文

我有两个数组:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧话新听 2024-10-17 04:53:31

您对 TreeMap 的使用方式感到困惑。 TreeMap 保持键的排序。在你的情况下,你有一个键 - intArray 所以没有什么可以排序的。您必须将每一对放入映射中:对于每个可能的 itheMap.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 possible i.

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 with Collections.sort(list). Of course you have to implement Comparable interface.

海未深 2024-10-17 04:53:31

是的,TreeMap 应该可以正常工作。但是,不要添加两个数组,而是添加每对值。

theMap.put(point1, worda);
theMap.put(point2, wordb);
theMap.put(point3, wordc);
theMap.put(point4, wordd);

Yes a TreeMap should work fine. However instead of adding both arrays add the each pair of values.

theMap.put(point1, worda);
theMap.put(point2, wordb);
theMap.put(point3, wordc);
theMap.put(point4, wordd);
夜未央樱花落 2024-10-17 04:53:31
for(int i=0; i< intArray.length; i++)
  theMap.put(intArray[i],strArray[i])
for(int i=0; i< intArray.length; i++)
  theMap.put(intArray[i],strArray[i])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文