Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - ArrayList default initial values

When you create an arraylist of type Integer in Java what are the default values? I need to check if an arraylist is full and I was going to get the size of the array then get the value at the last index and check if it was the default value.

Is there a better way? What would be the default value?

Hope that makes sense. Cheers

int size = a.size();
int last = a.get(size);
if( last == null )
{
    return true;
}else{
    return false;
}

Edit;

Is it possible to create an ArrayList with a max size that you can not go over to stop it dynamically expanding? When you create an ArrayList and you use size() would that return the actual size or the amount of elements in the arraylist? When doing this to create a max size would the default values be null?

public boolean isFull()
{
    int size = a.size();
    int last = 0;
    try{
        last = a.get(size-1);
    }catch (Exception e){
    }
    if( last == null )
    {
        return true;
    }else{
        return false;
    }
}

I currently have this, how does it look? Does this make sense now?

like image 575
Kyle93 Avatar asked Sep 02 '25 06:09

Kyle93


1 Answers

When you declare an ArrayList it is empty. It is also a dynamic container meaning it will grow so for you to ask if it is "full" is more of a constraint you'd need to add to your code.

So, if you want to achieve a goal like you describe.

List<Integer> list = new ArrayList<Integer>();
int MAX_ELEMENTS = 5; //Set this to however you want to constrain the datatype

public boolean addElement(Integer value) {
   if (list.size() < MAX_ELEMENTS) {
     list.add(value);
     return true;
   } else {
     return false;
   }
}

public boolean isFull() {
  return (list.size() == MAX_ELEMENTS);
}

public Integer getLast() {
  if (!list.isEmpty())
    return list.get(list.size()-1);
  else
    return null;
}

As others have stated though, if you generate a list with a preset size as such:

List<Integer> list = new ArrayList<Integer>(10);

You'd have a list of 10 elements large all being null in value. Should you add additional elements the list will still grow larger than 10 elements unless you constrain it like I did above.

like image 135
Grambot Avatar answered Sep 04 '25 20:09

Grambot