简体   繁体   中英

java.lang exception on casting int to string

I'm tasked to make a method that took two lists and found which integers in the lists are common. I decided to use ArrayLists because they are mutable, and a nested for loop to iterate over the two lists to determine the common integers. I wasn't sure if ArrayLists could be return types for methods, so I decided to try to make the ArrayList a regular array, but I got a java.lang exception with the following code. How should I fix it?

 import java.util.*; 
 import java.util.ArrayList;


public class Lab1InJava{
    public static void main(String [] args){
        ArrayList<Integer> listUno = new ArrayList<Integer>();

        listUno.add(4);
        listUno.add(3);
        listUno.add(2);
        listUno.add(1);

        ArrayList<Integer> listDos = new ArrayList<Integer>();

        listDos.add(4);
        listDos.add(3);
        listDos.add(2);
        listDos.add(1);

        System.out.println(inCommon(listUno, listDos));
    }

    public static Object[] inCommon(ArrayList<Integer> list1, ArrayList<Integer> list2){
        Collections.sort(list1);
        Collections.sort(list2);

        ArrayList<Integer> newList3 = new ArrayList<Integer>();
        for (int indexOne = 0; indexOne<list1.size(); indexOne++)
            for(int indexTwo = 0; indexTwo<list2.size(); indexTwo++)
                if (list1.get(indexOne) == list2.get(indexTwo))
                    newList3.add(list1.get(indexOne));

        Object[] newArray = newList3.toArray();

        for(Object o : newArray) {
            String s = (String) o;
            System.out.println(o);
        }
    return newArray;

    }   
}

Any object can be a return type, including an ArrayList . ArrayList has a method called contains, which can be used to compare lists as show below:

public static void main(String args[]) {
    ArrayList<Integer> listUno = new ArrayList<>();

    listUno.add(4);
    listUno.add(5);
    listUno.add(2);
    listUno.add(2);

    ArrayList<Integer> listDos = new ArrayList<>();

    listDos.add(4);
    listDos.add(3);
    listDos.add(2);
    listDos.add(2);

    System.out.println(inCommon(listUno, listDos));
}

public static ArrayList<Integer> inCommon(ArrayList<Integer> list1, ArrayList<Integer> list2) {
    ArrayList<Integer> list3 = new ArrayList<>();
    HashSet<Integer> set = new HashSet<>();

    for (int i : list1) {
        if (list2.contains(i)) {
            set.add(i);
        }
    }

    list3.addAll(set);

    return list3;
}

Output:

[2, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM