I am suppose to Write a test program that creates two MyArrayLists, list1 and li
ID: 3621842 • Letter: I
Question
I am suppose to Write a test program that creates two MyArrayLists, list1 and list2, with the initial values {"Tom", "George", "Peter", "Jean", "Jane"} and {"Tom", "George", "Michael", "Michelle", "Daniel"}, then invokes list1.addAll(list2), list1.removeAll(list2), and list1.retainAll(list2) and displays the resulting new list1.Here is what i got so far:
public class MyArrayListTest
{
public static void main(String[] args)
{
MyList<String> list1 = new MyArrayList<String> (
new String[]{"Tom", "George", "Peter", "Jean", "Jane"});
MyList<String> list2 = new MyArrayList<String> (
new String[]{"Tom", "George", "Michael", "Michelle", "Daniel"});
list1.addAll(list2);
list1.removeAll(list2);
list1.retainAll(list2);
System.out.println(list1);
}
}
Explanation / Answer
Hope this helps. Let me know if you have any questions. Please rate. :)
You're doing it just fine, but you may want to display the list after each operation. After the "removeAll" "retainAll" sequence, the list should be empty. (It retains only the elements in list 2, which you just removed, so nothing will be retained.)
Also, how come you're using "MyArrayList" instead of just "ArrayList"? And then also "MyList = new MyArrayList" - these types don't match, unless there's some inheritance I don't know about.
import java.util.*;
public class MyArrayListTest{
public static void main(String[] args) {
ArrayList list1 = new ArrayList(Arrays.asList("Tom",
"George", "Peter", "Jean", "Jane"));
ArrayList list2 = new ArrayList(Arrays.asList("Tom",
"George", "Michael", "Michelle", "Daniel"));
list1.addAll(list2);
System.out.println("list1 after addAll(list2): " + list1);
list1.removeAll(list2);
System.out.println("list1 after removeAll(list2): " + list1);
list1.retainAll(list2);
System.out.println("list1 after retainAll(list2): " + list1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.