Need help with some JAVA programming! Can someone post an example code coming fr
ID: 3848235 • Letter: N
Question
Need help with some JAVA programming! Can someone post an example code coming from the JAVA API?
Here is the JAVA API website for the first 2 examples: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
1.Write the clone method. It will make a copy of the existing list and return that copy. Also view the tester files for tests that guide how your solution should behave.
2.Write the equals method. It compares the item passed in against the current list for equality. Also view the tester files for tests that guide how your solution should behave.
Here is the JAVA API website for the third example: https://docs.oracle.com/javase/7/docs/api/java/util/List.html
3.Write the addAll method. See that file for directions on how the method should behave, but you are basically adding a List to the end of the existing linked list.
Explanation / Answer
Hi, Please find my code.
Please read my logic and you can modify according to your need.
import java.util.ArrayList;
import java.util.List;
public class JavaMethod {
public static <T extends Comparable<T>> List<T> clone(List<T> list) {
List<T> copy = new ArrayList<T>();
for(T item : list)
copy.add(item);
return copy;
}
public static <T extends Comparable<T>> boolean equals(List<T> list1, List<T> list2) {
if(list1 == null && list2 == null)
return true;
if(list1 == null || list2 == null)
return false;
if(list1.size() != list2.size())
return false;
for(int i=0; i<list1.size(); i++)
if(! list1.get(i).equals(list2.get(i)))
return false;
return true;
}
public static <T extends Comparable<T>> void addAll(List<T> list1, List<T> list2) {
if(list2 == null)
return;
if(list1 == null)
list1 = new ArrayList<>();
for(int i=0; i<list2.size(); i++)
list1.add(list2.get(i));
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(33);
list.add(23);
list.add(10);
System.out.println(list);
System.out.println(clone(list));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.