无法填充ArrayList

时间:2017-05-28 10:22:00

标签: java

我在下面有一个测试类,它调用我的shuffle类,它创建一个随机数的ArrayList并命令它们。当我从测试类中调用这个ArrayList时没有任何反应。

static ArrayList yup = new ArrayList();

public static void main(String[]args){
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a num to create a random list of numbers:  " );

    int guess = input.nextInt();
    shuffle y = new shuffle(guess);

    System.out.println(y.toString());

    ArrayList<Integer> jh = y.getnew_list();
    for(int d = 0; d < jh.size();d++){
        //System.out.println(three.get(d));
        System.out.println(jh.get(d));
    }

    shuffle one = new shuffle(guess);   
}

随机播放课程:

import java.util.*;    
import java.util.Random;

public class shuffle implements Comparable <shuffle> {

    static int size;   
    static ArrayList new_list = new ArrayList();

    shuffle(int size){
        this.size = size;
        Random rand = new Random();

        for(int i = 0; i<new_list.size();i++){
            int  t = rand.nextInt(50) + 1;
            new_list.add(t);               
        }     
    }

    public ArrayList getnew_list(){
        return this.new_list;   
    }

    public int getSize(){   
        return size;
    }  

    public String toString(){
        String str = new String();

        for(int i = 0; i<new_list.size();i++){
            str += "  " + new_list.get(i);
            System.out.println(str);
        }

        return str;
    }

    public int compareTo(shuffle that) {   
        if(this.getSize() > that.getSize()){
            return 1;
        }
        if(this.getSize() < that.getSize()){
            return -1;
        }
        else
            return 0;   
    }
}

1 个答案:

答案 0 :(得分:1)

在shuffle类中,你没有初始化size变量,而是将它作为未初始化的变量使用,这可能是其中一个原因。

 import java.util.*;

 import java.util.Random;

public class shuffle implements Comparable <shuffle> {

   static int size;

  static ArrayList new_list = new ArrayList();

  shuffle(int size){
  this.size = size;
  Random rand = new Random();

  for(int i = 0; i<new_list.size();i++){
     int  t = rand.nextInt(50) + 1;
     new_list.add(t);