Question 1: Write the following method that returns a new ArrayList. The new list contains the nonduplicate elements from the original list,
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list)
Question 2:
Implement the following method that returns the maximum element in an array:
public static <E extends Comparable<E>> E max(E[] list)
Each question is its own code and it must be able to run. Please show details .
Thank you in advance!
import java.util.ArrayList; import java.util.Arrays; public class RemoveDuplicates { public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) { ArrayList<E> newList = new ArrayList<>(); for(int i = 0; i < list.size(); ++i) { if(!newList.contains(list.get(i))) { newList.add(list.get(i)); } } return newList; } public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 8, 2, 8, 1, 4, 2, 6)); System.out.println("Original list = " + numbers); System.out.println("List after removing duplicates = " + removeDuplicates(numbers)); } }
public class GenericMaxComparable { public static <E extends Comparable<E>> E max (E [] list) { E maxValue = list[0]; for(int i = 0; i < list.length; i++) { if(list[i].compareTo(maxValue) > 0) { maxValue = list[i]; } } return maxValue; } public static void main(String[] args) { String[] colors = {"Red","Green","Blue"}; Integer[] numbers = {1, 2, 3}; Double[] doubles = {3.0, 5.9, 2.9}; System.out.println("Colors: " + max(colors)); System.out.println("Numbers: " + max(numbers)); System.out.println("Circle11 Radius: " + max(doubles)); } }
Get Answers For Free
Most questions answered within 1 hours.