0

I'm trying to create a simple generic method that swaps two entries in an array but when I call the method it gives the the following error. What am I missing? I'm sure it's an easy fix I just can't see it.

Sorting.java

package testing;

import java.util.Comparator;

public class Sorting {

    public static <T> void swap(T[] array, int left, int right){
        T temp = array[right];
        array[right] = array[left];
        array[left] = temp;
    }
}


SortTest.java

package testing;

import static testing.Sorting.*;

public class SortTest {

    public static void main(String[] args){

        int[] nums = {5, 12, 3, 7, 2};
        swap(nums, 0, 1);
    }
}
spencer.sm
  • 19,173
  • 10
  • 77
  • 88

3 Answers3

2

There is no way in Java to make a generic method that allows primitives to be accepted. You cannot pass an int[] to a method that expects a T[], nor can you make any method generic over different kinds of primitives. You could use a boxed array like Integer[], or you could custom-write an overload that accepted an int[].

You also have the problem that you would need to write Sorting.swap(nums, 0, 1) instead of just swap(nums, 0, 1), or you would need to write import static testing.Sorting.swap; as an import statement.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • @wero added that in too. – Louis Wasserman Feb 17 '16 at 22:11
  • It is possible to make a method that accepted all types of arrays (primitive arrays and reference arrays), by taking type `Object`, and it would be able to operate on the array without caring about the element type by using reflection. However, this wouldn't be a generic method, nor would it be type-safe. – newacct Feb 18 '16 at 22:54
2

The method signature is a generic Object[] which you can't assign an int[]

int[] nums = {1};
Object[] o = nums; // doesn't compile

And hence the method won't allow it. You can use Integer[] instead.

Integer[] nums = {5, 12, 3, 7, 2};

Note that auto-boxing doesn't work with arrays, when generics methods allow primitives, there is auto-boxing behind the scenes.

Generics and primitives types don't play well together. (Things might get better in Java 10)

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0
  1. swap method is a static one, though one that is specific to a class. In order to call it you need the className.method or instanceOfClass.method (this will be translated at compile time in class.method)
  2. Generic cannot be applied to primitives: see Why don't Java Generics support primitive types?
Community
  • 1
  • 1