get value from list
This book is now obsolete Please use CSAwesome instead. You can get the object at an index using obj = listName.get(index) and set the object at an index using listName.set(index,obj). Note Remember that you can get the value at an array index using value = arrayName[index]. This is different from how you get the value from a list using obj = listName.get(index). You can set the value at an index in an array using arrayName[index] = value, but with lists you use listName.set(index, object). You can also remove an object at an index in a list using remove(index) which returns the removed object and shifts the remaining objects past the index left one index. Note The remove(int index) method will remove the object at the index and shift left any values to the right of the current index. It doesnt remove the object that matches the integer value given. In the example above it doesnt remove the 1. It removes the 2 at index 1. Check your understanding
8-6-3: What will print when the following code executes? List list1 = new ArrayList();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.set(2, new Integer(4));
list1.add(2, new Integer(5));
list1.add(new Integer(6));
System.out.println(list1);
You can step through the code above by clicking on the following Example-8-6-1.
8-6-4: What will print when the following code executes? List list1 = new ArrayList();
list1.add("Anaya");
list1.add("Layla");
list1.add("Sharrie");
list1.set(1, "Destini");
list1.add(1, "Sarah");
System.out.println(list1);
You can step through the code above by clicking on the following Example-8-6-2.
8-6-5: What will print when the following code executes? List numList = new ArrayList();
numList.add(new Integer(1));
numList.add(new Integer(2));
numList.add(new Integer(3));
numList.set(2,new Integer(4));
numList.add(1, new Integer(5));
numList.add(new Integer(6));
System.out.println(numList);
You can step through the code above by clicking on the following Example-8-6-3.
8-6-6: What will print when the following code executes? List list1 = new ArrayList();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.remove(1);
System.out.println(list1);
You can step through the code above by clicking on the following Example-8-6-4.
8-6-7: What will print when the following code executes? List list1 = new ArrayList();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.remove(2);
System.out.println(list1);
You can step through the code above by clicking on the following Example-8-6-5. You have attempted of activities on this page |