有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (4) 个答案

  1. # 1 楼答案

    使用ArrayList

    function ArrayList<Integer> foo(){
        List<Integer> l = new ArrayList<Integer>();
        l.add(1); // add number 1 to the list
        return l;
    }
    

    或者看看这个:http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs

    You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).

    To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

  2. # 2 楼答案

    public int[] foo() {
    
      List<Integer> list=new ArrayList<>();
      //list size is not fixed, u can use it
    
      //At the end convert it to int array
      int[] intArray = list.stream().mapToInt(Integer::intValue).toArray();
    
      return intArray;
    }
    
  3. # 3 楼答案

    你可以这样做:

    public int[] test ( int[]b )
    {
        ArrayList<Integer> l = new ArrayList<Integer>();
        Object[] returnArrayObject = l.toArray();
        int returnArray[] = new int[returnArrayObject.length];
        for (int i = 0; i < returnArrayObject.length; i++){
             returnArray[i] = (Integer)  returnArrayObject[i];
        }
    
        return returnArray;
    }   
    
  4. # 4 楼答案

    我得到了这个答案。。这个很好用。。谢谢大家的意见

    public static int[] convertIntegers(List<Integer> integers)
    {
        int[] ret = new int[integers.size()];
        Iterator<Integer> iterator = integers.iterator();
        for (int i = 0; i < ret.length; i++)
        {
            ret[i] = iterator.next().intValue();
        }
        return ret;
    }