如何在数组中插入项?

时间:2014-09-01 05:13:54

标签: java

我的代码数组。如何在数组中插入项目?

int listElemCount = jCBWorkerMen.getItemCount();
Object[] selectionValues = null;
for (int i = 0; i < listElemCount; i++) {
        selectionValues[i]  =  (Object[]) jCBWorkerMen.getItemAt(i);
        System.out.println(selectionValues);
     }
String initialSelection = "Dogs";
Object selection = JOptionPane.showInputDialog(null, "What are your favorite   animals?", "Zoo Quiz", JOptionPane.QUESTION_MESSAGE, null, selectionValues,  initialSelection);
System.out.println(selection);

3 个答案:

答案 0 :(得分:0)

如下所示

public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        list.add(9);
        list.add(10);

        Object[] selectionValues = new Object[list.size()];
        for (int i = 0 ; i < list.size() ; i++) {
            selectionValues[i] = list.get(i);
        }

        for (int i = 0 ; i < selectionValues.length ; i++) {
            System.out.println(selectionValues[i]);
        }
    }

答案 1 :(得分:0)

你的算法不正确,这个

int listElemCount = jCBWorkerMen.getItemCount();
Object[] selectionValues = null;
for (int i = 0; i < listElemCount; i++) {
   selectionValues[i]  =  (Object[]) jCBWorkerMen.getItemAt(i);
   System.out.println(selectionValues);
}

需要从初始化数组开始。此外,在完成初始化之前,您可能不应该打印阵列。最后,您需要使用Arrays.toString(Object[]),因为Java数组不会覆盖toString()。等等,

int listElemCount = jCBWorkerMen.getItemCount();
Object[] selectionValues = new Object[listElemCount];
for (int i = 0; i < listElemCount; i++) {
    selectionValues[i] = jCBWorkerMen.getItemAt(i);
}
System.out.println(Arrays.toString(selectionValues));

答案 2 :(得分:0)

更改代码应如下所示

int listElemCount = jCBWorkerMen.getItemCount();
    Object[] selectionValues = new Object[listElemCount];
    for (int i = 0; i < listElemCount; i++) {
            selectionValues[i]  = jCBWorkerMen.getItemAt(i);
            //System.out.println(selectionValues);
         }
   //to view the all the items in the array
   for (int i = 0; i < listElemCount; i++) {            
            System.out.println(selectionValues[i]);
   }
    String initialSelection = "Dogs";
    Object selection = JOptionPane.showInputDialog(null, "What are your favorite   animals?", "Zoo Quiz", JOptionPane.QUESTION_MESSAGE, null, selectionValues,  initialSelection);
    System.out.println(selection);