Sam Hooper
Sam Hooper

Reputation: 307

Java: How to use Arrays.copyOfRange() with generic types?

I am trying to make a method called "sub," which returns a substring when a String is passed as the first argument, and a subarray when an array is passed as the first argument. For example:

sub("hello", 1, 3) returns "el"

sub(new String[]{"a","b","c","d"}, 1, 3) returns a String array containing {"b","c"}

sub(new Integer[]{1,2,3,4}, 0, 2) returns an Integer array containing {1,2}

I have got the String part to work, but I cannot figure out the array part. Here is my code so far (I am assuming that the start and end indexes are valid):

public static <T extends Object> T sub(T obj, int start, int end){
        if(obj instanceof String){
            return ((T) (((String) obj).substring(start, end)));
        }
        else if(obj != null && obj.getClass().isArray()){
            return (???)
        }
        else return null;
    }

I would like to use Arrays.copyOfRange() to create the subarray, but it doesn't really matter how I create it.

Here are all of the things I've tried in place of the return (???) statement:

return Arrays.copyOfRange(obj, start, end);
return (T) Arrays.copyOfRange(obj, start, end);
return (T) Arrays.copyOfRange(obj, start, end, T);

Any help with this would be greatly appreciated. I'm very new to working with generics, so I'm sorry if this is not something that's possible with them. If you see any other flaws in my code, don't hesitate to point them out. Thanks!

Upvotes: 0

Views: 692

Answers (1)

azro
azro

Reputation: 54168

A working version could be the following, but I'm not very convince that this is the best way, but it may help you now, or someone else could take it to improve it :

private static <T> T sub(T obj, int start, int end) {
    if (obj instanceof String) {
        String v = (String) obj;
        return (T) v.substring(start, end);
    } else if (obj != null && obj.getClass().isArray()) {
        Object[] v = (Object[]) obj;
        return (T) Arrays.copyOfRange(v, start, end);
    } else {
        return null;
    }
}


public static void main(String[] args) {
    System.out.println(sub("hello", 1, 3));                                          // el
    System.out.println(Arrays.toString(sub(new String[]{"a", "b", "c", "d"}, 1, 3)));//[b,c]
    System.out.println(Arrays.toString(sub(new Integer[]{1, 2, 3, 4}, 0, 2)));       //[1,2]
}

Upvotes: 1

Related Questions