Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to loop through a userSet with where the id's in the array userSet are Int. I keep getting this error: java.lang.Integer cannot be cast to java.lang.Long

Is there a simple way to do this? Casting variables are easy but is there an easy way to cast all variables in an array to Long? Very new to Java here.

Set <Long> userSet = getUniqueFollowers("/tmp/followers.txt")

for (long id : userSet) {
     System.out.println("Starting twitter account: " + id);
share|improve this question
    
Is there a specific reason you want them to be long? Because it seems to me that you could just use int and it would work. –  zneak May 14 at 0:47
    
First, as you've clearly discovered you can't do it with a cast. Second, what does getUniqueFollowers return? --- Set<Integer>? –  Elliott Frisch May 14 at 0:48
    
Also a Set is not an array –  RichN May 14 at 0:51

1 Answer 1

Parameterization of collection intended right to not getting cast-exceptions and to know type of elements of collection, to know "what is inside" (however you can hide parameter-type at will)

So "set of integers" can not be cast to "set of longs" straight. You only can create a new set and fill it with elements one by one.

Anyway, why do you need to cast collection to Set<Long>? Why not Set<Integer> (as I understand — what is the return type of method). Or, as I said, you may hide param and just type Set userSet = ...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.