Search code examples
javaandroidrandomarraylistlogcat

ArrayList not storing values


I am new to the concept of ArrayLists. I am using them as I want a dynamic array that isn't limited in the size of how many values it can hold in sequence. But the method I am using is not storing values correctly. I only keeps one value being the value 1. My code is as follows:

public void Rand(){
Random rand = new Random();
int Val = rand.nextInt(5); 
ArrayList<Integer> ValList = new ArrayList<Integer>();
ValList.add(Val);
Log.d("LOOK", Integer.toString(ValList));   
Log.i("VALUE LIST ", ValList.size()+" <<<<LIST HERE"); }

This process is called in oncreate and then returned to on a loop Ideally every time this class runs a new random number will be added to the array in sequence.

This is the relevant info on the logcat:

03-05 19:15:15.020: D/LOOK(21325): 3
03-05 19:15:15.020: I/VALUE LIST(20883): 1 <<<<LIST HERE
03-05 19:15:15.040: D/LOOK(21325): 5
03-05 19:15:15.040: I/VALUE LIST(20883): 1 <<<<LIST HERE

As you can see it only stores the value 1 even though the random value is not 1. Am I using the wrong type of array or implementing it incorrectly?

The output i'd want to see is something like this:

03-05 19:15:15.020: D/LOOK(21325): 3
03-05 19:15:15.020: I/VALUE LIST(20883): 3 <<<<LIST HERE
03-05 19:15:15.040: D/LOOK(21325): 5
03-05 19:15:15.040: I/VALUE LIST(20883): 3, 5 <<<<LIST HERE

Solution

  • Because, Your ArrayList<Integer> ValList = new ArrayList<Integer>(); has local scope for Rand() method only, So its has new instance every time you called Rand() function.

    Just declare ArrayList<Integer> ValList = new ArrayList<Integer>(); as class level scope.

    And use,

    Like,

    // Class level member declaration
    ArrayList<Integer> ValList = new ArrayList<Integer>();
    
    public void Rand(){
              Random rand = new Random();
              int Val = rand.nextInt(5); 
    
              ValList.add(Val);
              Log.d("LOOK", ValList.toString()); 
              // Also here you are printing size of Arraylist not a content of arraylest
              Log.i("VALUE LIST ", ValList.size()+" <<<<LIST HERE"); 
     }
    

    To print specific object value you have to get object from ArrayList using .get() with position of object, or use .toString() to print all list contents

    Log.i("VALUE LIST ", ValList.toString()+" <<<<LIST items"); // using .toString() to print all contents of List
    

    Update:

    As I have doubt over this line throws Exception (But from your logcat its working fine, as list contains only one item)

    Log.d("LOOK", Integer.toString(ValList)); 
    

    As you are trying to print values of list valList, simply use .toString() like, ValList.toString()