new to Java. Trying to understand the point of declaring my ArrayList as an <Integer>. I still have to cast my .get() result as an int in my methods for it to work, else it still returns an Object. eg: (int) deliv.get(j) int the Sort method's for loop. Is there a way to avoid this or is my code the correct approach?
Problem: Assume the array can change size, hence not just using primitive array. All numbers should be pairs, looking for the unique one missing it's pair value. I sort the array, then cycle through the pairs to look for a mismatch. Thanks.
import java.util.*; class StolenDrone{ public static void main(String[] args){ ArrayList<Integer> deliv_id = new ArrayList<>(); deliv_id.add(99); deliv_id.add(13); deliv_id.add(4); deliv_id.add(5); deliv_id.add(8); deliv_id.add(99); deliv_id.add(8); deliv_id.add(5); deliv_id.add(4); System.out.println("Array is: " + deliv_id); sort(deliv_id); System.out.println("Array is: " + deliv_id); int unique = findUnique(deliv_id); System.out.println("Unique ID is: " + unique); } //Sort ArrayList into increasing order static void sort(ArrayList deliv){ int temp; for(int i = 0; i<deliv.size();i++){ for (int j=0; j<deliv.size()-1;j++){ if((int) deliv.get(j)> (int) deliv.get(j+1)){ temp = (int) deliv.get(j+1); deliv.set(j+1, deliv.get(j)); deliv.set(j, temp); } } } } //check pairs in ArrayList to find unique entry static int findUnique(ArrayList deliv){ for(int i = 0; i<deliv.size()-1;i+=2){ if(deliv.get(i) == null){ return -1; //no unique } if((int) deliv.get(i) != (int) deliv.get(i+1)){ return (int) deliv.get(i); } } return -1; } }
ArrayList<Integer>makesget()to return Integer; and as Integer and int is not the same, you need to "cast".