【问题标题】:How to write a generic method to insert an element in an array?如何编写通用方法在数组中插入元素?
【发布时间】:2015-07-23 22:44:16
【问题描述】:

我有一个输入数组 [3, 5, 12, 8],我想要一个与输入相同的输出数组(输入不得受影响),但元素 7 插入在 5 到 12 之间,所以在索引处输入数组的 2 个。

这是我目前所拥有的。我注释掉了无法通过事件编译的代码,并添加了在尝试这种或那种方式时出现的几个问题:

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;
}

数组组件类型可以是String、Integer甚至是JPanel。

【问题讨论】:

  • @SLaks 不能做什么?在我的方法中初始化 obj?
  • 那应该怎么做?
  • @Raffaele 它应该创建一个输入对象的数组并指定特定索引的内容。
  • add.getClass().newInstance() 如果你有一个空的构造函数应该可以工作。
  • out.set(newIndex, add) 不起作用,因为new ArrayList&lt;&gt;(newIndex + 1)ArrayList 分配了newIndex + 1 元素的空间,但它是空的;您不能在中间随机设置索引。您必须首先用newIndex 元素实际填充ArrayList;你不能 set 一个元素的索引大于当前大小。

标签: java android generics methods


【解决方案1】:

这是代码的通用版本

@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;
}

但您可能想要专门化处理原始类型的方法。我的意思是,泛型和数组不能很好地混合——所以你会遇到 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});
}

【讨论】:

  • 我明白了。我什至不知道arraycopy。这将非常有用。关于使用包装器类型(如果是整数,则为整数,对),我想强制转换应该解决这个问题。非常感谢。
  • 我的意思是,也许你会发现处理包装器很乏味。如果它是库代码,请考虑至少对于 int 和 doubles 的类似方法。另外,如果它解决了您的问题,请点赞并接受此答案
【解决方案2】:

你可以这样做。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2021-08-06
    • 2021-05-31
    相关资源
    最近更新 更多