How do you clear a array?

edited August 2015 in How To...

yep.

also, (how do you do a lenny?)

Answers

  • You can't "clear" an array but maybe you're looking for something like this?

    Object[] o = new Object[10]; //an Array
    o = null;
    

    or

    for(Object obj : o)
    {
       obj = null;
    }
    
  • edited August 2015

    so if I had an array like

    String[] str = {"hi","hello","hey"};

    and then did

    str = null;

    str would then be {} ?

    @colouredmirrorball

  • edited August 2015
    • We can change the content of Java's regular arrays. But we can't change their length! [-X
    • That is, the # of element indices are determined at the creation of the array and stays so!
    • If we need a different size, we gotta make a new array and arrayCopy() the old into the new.
    • If we simply wanna "reset" their content, we can use Arrays.fill() in order to fill up the whole array w/ a chosen value, like 0 or an "" empty String for example:
      https://docs.Oracle.com/javase/8/docs/api/java/util/Arrays.html#fill-java.lang.Object:A-java.lang.Object-
  • edited August 2015
    String[] interjections = {"hi", "hello", "hey"};
    println(interjections);
    println();
    
    java.util.Arrays.fill(interjections, "");
    printArray(interjections);
    
    exit();
    
  • If you want every element to become an empty string then iterate over the array and assign each element to be an empty string

    If you want to take an array that has say 3 elements and make it so that it has no elements then you should not be using an array. You want to use an ArrayList which can have its size changed

  • edited August 2015 Answer ✓

    For a more specialized dynamically-sizable String container, what about StringList: :D
    https://Processing.org/reference/StringList.html

  • edited August 2015 Answer ✓

    If you had
    String[] str = {"hi","hello","hey"};
    and did
    str = new String[0];
    str would then be {} ?

    Try it with this

    String[] str = { "hi", "hello", "hey" };   
    println("#");
    for (String s : str)
        println(s);
    
    str = new String[0];
    println("#");
    for (String s : str)
        println(s);
    
    println("#");
    
    // Now the array has no elements so attempting to use 
    // the array would cause an index out of range exception
    

    Output is

    #
    hi
    hello
    hey
    #
    #
    
  • thanks everyone! that helped a lot. :)

    I have asked many questions about a program I have been doing (this being one of them) and I hope to be able to show you a PREVIEW of it soon! :D

Sign In or Register to comment.