3

I am getting below Error with the below code. is there any alternate way to do this.

I am getting [I cannot be cast to java.lang.Integer] Error with the below code. is there any alternate way to do this.

package collectionTest;

import java.util.*;

public class ContinuesNumber {

    public static void main(String[] args) {

     int[] num = new int[]{3,5,81,6,3,789,67,56,79,8,76,80,6,77,7};

     List<Integer> list = new ArrayList(Arrays.asList(num));

     Set<Integer> count = new HashSet<Integer>();
     Set<Integer> tmp = new HashSet<Integer>();

     for(Integer i=0;i<list.size();i++)
     {
         int var = list.get(i);

         int incr = var+1;
         int decr = var-1;

         tmp.add(list.get(i));
         for(Integer j=i+1;j<list.size();j++)
         {
             if(incr==list.get(j) || decr==list.get(j))
             {
                    tmp.add(list.get(j));
                    if(list.get(j)>list.get(i))
                        incr++;
                    else
                        decr--;
                    continue;
             }
             else
             {
                list.remove(list.get(j));
             }
        }
     }
     if(count.size()>tmp.size())
     {
         count.addAll(tmp);
     }

     System.out.println("most continuous elements are : "+ count);
   }
}
Vikas Rajak
  • 49
  • 1
  • 1
  • 7

2 Answers2

1

Try to use int instead Integer in all of your for loop like this:

    for(int i=0;i<list.size();i++)

And:

   for(int j=i+1;j<list.size();j++)

And try to write the array num of Integer like this:

    Integer[] num = new Integer[]{3,5,81,6,3,789,67,56,79,8,76,80,6,77,7};
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
1

You should be using int instead of Integer. Change both the for loops in your program like this:

for(Integer i=0;i<list.size();i++) to for(int i=0;i<list.size();i++)

for(Integer j=i+1;j<list.size();j++) to for(int j=i+1;j<list.size();j++)

Also, you can't do this:

List<Integer> list = new ArrayList(Arrays.asList(num));

The right way is:

int[] num = new int[]{3,5,81,6,3,789,67,56,79,8,76,80,6,77,7};
List<Integer> list = new ArrayList<Integer>();
for (int index = 0; index < num.length; index++)
{
    list.add(num[index]);
}
user2004685
  • 9,548
  • 5
  • 37
  • 54