I have a weird problem (please have in mind I reently started learning) the toString method ArrayList in let's say ArrayList(5) shows []
but this class whih is similar would show [null, null, null, null, null]
before ArrayList was showing nulls as well and I was happy and all was working fine (did i imagine it?) I need ArrayList to show me nulls like the link eample. Please help me
import java.util.ArrayList; public class testArray { public static void main (String[] arg){ List myList = new ArrayList(5); System.out.print(myList); } }
Edit: I think I didn't explain myself (I apologies). I DO want to create an empty list but I want null references instead of an empty list. I'm sure it's something dumb I'm not seeing
Edit2: I got it!...im sorry i wasnt able to be understood but this is what I wanted..
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i<elem.length; i++) {
sb.append(elems[i]);
sb.append(", ");
}
return sb + "]\n" + elem.length+"\n";
}
I just had to oerride the tostring method so i would show the results as null :D thank you anyways!!! now i dont know how to close the post :P :P
This code will initialize all your list
elements to null
import java.util.ArrayList;
import java.util.Collections;
public class TestArray {
public static void main(String[] arg) {
ArrayList<Object> list = new ArrayList<Object>(Collections.nCopies(5, null));
System.out.println(list);
}
}
output: [null, null, null, null, null]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.