lab22
subdirectory of your personal repo, the other submits a file report.txt
in the lab22
subdirectory of your personal repo.java.lang.ArrayList
class have? Which are not static? What are their types? (Hint: Modify one of the programs from the slides.)
ArrayList
as
ArrayList<String> myList = new ArrayList<>(); myList.add("Hello"); myList.add("World");Using reflection, list the contents of the
size
field. What is it, and how did you get it?size
to have value 1000. How do you do that? (Hint: To avoid dealing with the pesky exceptions, add throws Exception
to the main
method.myList
. What happens?length
field? Let's try. What are all fields of the class String[].class
?array.length
is just syntax, not an actual field. Instead, let's do this:
public static Object[] grow(Object[] a, int newLength) throws Exception { Object[] newArray = new Object[newLength]; for (int i = 0; i < Math.min(a.length, newLength); i++) newArray[i] = a[i]; return newArray; }Try it out:
String[] words = "Mary had a little lamb".split(" "); String[] moreWords = grow(words, 10); System.out.println(moreWords.length); System.out.println(moreWords[0].length());What happens?
String[] moreWords
to Object[] moreWords
? moreWords
back to a String[]
and apply a cast (String[])
. Does the program compile now?grow
. It needs to make an array of the correct component type, not Object
. The correct type is the component type of a
. How can you find it? (Look into the API of java.lang.Class
.)new Object[newLength]
to a call to (Object[]) Array.newInstance(...)
. See the API of java.lang.reflect.Array
. Can you now call (String[]) grow(words)
?grow
to grow an array of int
values? What happens if you try?grow
work for primitive type arrays. In step 3, why didn't Array.newInstance
return an Object[]
? (Hint: What if the component type is int.class
?)Object[]
cast and declare newArray
as an Object
. What happens?newArray[i] = ...
to set the new array value. Use Array.set
instead. Does the program compile?Object
. Double-check that you can still grow an array of strings.int[]
array because the parameter type is still Object[]
. What happens if you change it to Object
?int
array?