0

I have the following code:

public static void poistaKaikki32(LinkedList L1, Collection L2) {
        LinkedList<Integer> temp = new LinkedList<>();
        HashSet<Integer> L2Set = new HashSet<>(L2); 

        // first filter elements into temp
        while (L1.size() > 0) { // n loops
            int v = L1.removeFirst(); <--- getting error cannot convert object to int
            if (!L2Set.contains(v)) { 
                temp.addLast(v);      
            }
        }

        // add filtered values back to L1
        while (temp.size() > 0) {    
            L1.addLast(temp.removeFirst()); 
        }


    }

I keep getting an error on int v = L1.removeFirst();. How would i fix this, without using casts.

Masteprh33r
  • 105
  • 9
  • What is return type of `removeFirst()` ? – Sudhir Ojha Oct 11 '18 at 10:09
  • 1
    If the parameter `L1` is a `LinkedList` containing `Integer`s, then declare it as `LinkedList L1`; if you can't do that due to negative impact on calling code, you'll have to use an `(Integer)` cast. – Kevin Anderson Oct 11 '18 at 10:17
  • And: learn about java naming conventions. Variable/parameter names go camelCase. And: use **meaningful** that tell human readers what is going on. L1 has no meaning and tells nothing. – GhostCat Oct 11 '18 at 10:21
  • Yeah, @luk2302, a cast isn't optimal; but what to do if there's a ton of stuff calling this thing with raw `List`s? – Kevin Anderson Oct 11 '18 at 10:33

2 Answers2

1

Please try

Integer v = (Integer)L1.removeFirst();
Deepak Jain
  • 347
  • 1
  • 6
  • 2
    well, it "fixes" the compiler error by basically ignoring it. This is not a proper answer. Change the type of `L1` instead. – luk2302 Oct 11 '18 at 10:15
  • @luk2302 Actually you are right `public static void poistaKaikki32(LinkedList L1, Collection L2) {` – Masteprh33r Oct 11 '18 at 10:18
1

argument to method is of raw type thats why when you do a get operation on it you get an object type .to make this work either TYPECAST it while doing a get operation using Integer v = (Integer)L1.removeFirst();

or change the method parameter type LinkedList L1 to LinkedList<Integer> L1

but best way to do it is second one change the parameter type

Nawnit Sen
  • 973
  • 2
  • 7
  • 14