简体   繁体   English

如何编写通用方法在数组中插入元素?

[英]How to write a generic method to insert an element in an array?

I have an input array [3, 5, 12, 8] and I want an output array (the input must not be affeccted) identical to the input, but with the element 7 inserted between 5 and 12, so at index 2 of the input array. 我有一个输入数组[3,5,12,8],我想要一个与输入相同的输出数组(输入必须不受影响),但是在5和12之间插入元素7,所以在索引2处输入数组。

Here is what I have so far. 这是我到目前为止所拥有的。 I commented out code that doesn't event compile, and added a couple of questions that arose while trying this or that way: 我注释掉了没有事件编译的代码,并添加了一些在尝试这种或那种方式时出现的问题:

public static <O>ArrayList<O> addToSet(O[] in,O add,int newIndex){
//    O obj = (O) new Object(); //this doesnt work
//    ParameterizedType obj = (ParameterizedType) getClass().getGenericSuperClass(); // this is not even recognized
    ArrayList<O> out = multipleOfSameSet(obj, in.length);
    if (newIndex > in.length){
        out = new ArrayList<>(newIndex+1); // also noticed that initializing an ArrayList 
        //like this throws an IndexOutOfBoundsException when i try to run out.get(),
        // could someone explain why??  
        out.set(newIndex, add);
    }
    int j = 0;
    int i = 0;
    while(j<in.length+1){
        if (j==newIndex){
            out.set(j, add);
        } else if(i<in.length){
            out.set(j, in[i]);
            i++;
        }
        j++;
    }
    return out;
}

The array component type could be String, Integer or even a JPanel. 数组组件类型可以是String,Integer甚至是JPanel。

Here is the generic version of the code 这是代码的通用版本

@SuppressWarnings("unchecked")
public <T> T[] insertInCopy(T[] src, T obj, int i) throws Exception {
    T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length + 1);
    System.arraycopy(src, 0, dst, 0, i);
    dst[i] = obj;
    System.arraycopy(src, i, dst, i + 1, src.length - i);
    return dst;
}

but you may want to specialize the method for dealing with primitive types. 但您可能希望专门处理基本类型的方法。 I mean, generics and arrays don't mix well - so you'll have troubles with int and will need to use wrapper types: 我的意思是,泛型和数组不能很好地混合 - 所以你会遇到int问题,需要使用包装器类型:

@Test
public void testInsertInTheMiddle() throws Exception {
    Integer[] in = {3, 5, 12, 8};
    Integer[] out = target.insertInCopy(in, 7, 2);
    assertEquals(out, new Integer[] {3, 5, 7, 12, 8});
}

You can do this way. 你可以这样做。

static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
    for (T o : a) {
        c.add(o);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM