How do you set an object in array to null value?
Hi, I'm going to try to make my query as brief as possible because my code is very long. Please excuse me.
I'm trying to replace (set) an object in my array to null. Lets say my array is "numbers" and "item" is the index of a particular object in the array.
I tried:
Is this correct? I get the error: "cannot find symbol - method set(int, <nulltype>)"
I have never used "null" before, so any feedback is certainly welcome, but from what I know, null does nothing to change the size of the array -- it simply makes the value an empty hole.
Re: How do you set an object in array to null value?
Arrays are the exception in Java. instead of using a method, arrays are set directly, using square brackets to get both the indexed element and to set the data.
Code :
// getting back an index value
int[] numbers = new int[5];
int[0] = 5; // setting
System.out.println(int[0]); // getting
Object arrays are the same as primitive arrays except that you can give them a null value.
Code :
String[] list = new String[5];
String[0] = null;
Re: How do you set an object in array to null value?
Thank you for answering. I understand that way of setting, but isn't there a specific set method I can use for arrays (it is in the API I believe). Also, what are primitive arrays..? I thought arrays could only hold objects, so not ints, but only the Integer class, for example. Anyways, I will use your advice. Thanks again!
Re: How do you set an object in array to null value?
Arrays don't really have any methods defined, but to have the special method of getting/setting. Primitive arrays are simply arrays of primitives. They can hold any data type (primitive or object).
I think what you're trying to reference to is an ArrayList. These can only hold object (because of generics implementation in Java, but that's a whole other can of worms). ArrayList does not have any of those square brackets stuff, and must be accessed in the way every other object can be.
Code :
ArrayList<String> myStrings = new ArrayList<String>(5); // initial capacity of 5
myStrings.set(0,null); // sets element 0 to null
Re: How do you set an object in array to null value?
Ah yes I know ArrayLists ahah I love them. All right, you cleared a lot of things up. Thanks for everything.
Re: How do you set an object in array to null value?
Always remember there is no such thing as a primitive array. An array is always an object. However an array can still take primitives.
// Json