【问题标题】:Why does index = -1 when the elements exist in the array? [duplicate]当元素存在于数组中时,为什么 index = -1? [复制]
【发布时间】:2015-02-11 14:24:57
【问题描述】:
public void swap(int a, int b) {                                                                                                                                                                                          
    int indexA = Arrays.asList(nums).indexOf(a);
    int indexB = Arrays.asList(nums).indexOf(b);

    nums[indexA] = b;
    nums[indexB] = a;
}
public void selectionSort() {
    int x = 0;
    findIndexOfMinAfter(0);
    swap(nums[x], nums[x + 1]);
}

int[] nums 是我传入的一个数组。当我调用 swap 方法时,ab 都存在于数组中,但 indexAindexB 返回 -1。知道为什么会这样吗?

【问题讨论】:

    标签: java arrays indexing selection-sort


    【解决方案1】:

    Arrays.asList 是一个接受对象数组的通用方法。在这种情况下,整个int 数组被视为一个对象,因为它的元素是基本类型int。因此,Arrays.asList 返回的是数组列表而不是整数列表。

    您可以通过将nums 转换为Integers 的数组来解决此问题:

    Integer[] nums;  // instead of int[]
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多