Robin
Robin

Reputation: 143

Generic methods

I need to send an integer array and a string array to this generic method and find out if a certain number or string is present there or not.I wrote this code but it is giving an error on the line if(e==30) saying that "Incompatible operand types E and int". Please help.

public class Ch2Lu3Ex2
 {
   public static <E> void searchArray(E[] inputArray)
   {
    for(E e : inputArray)
     {
       if(e==30)
         {
          System.out.println("Element found in integer array");
         }
       else if(e=="raj")
         {
           System.out.println("Element found in string array");
         }

     }
  } 

 public static void main(String[] args)
  {
       Integer[] integerArray = {10,20,30};
       String[] stringArray = {"robin","raj","ravi"};
       searchArray(integerArray);
       searchArray(stringArray);
    }
  }

Upvotes: 1

Views: 222

Answers (3)

Andremoniy
Andremoniy

Reputation: 34900

There are two mistakes, both of them must be fixed:

1) fix it like: if(e instanceof Integer && (Integer)e==30) - you have to check, that e is an instance of Integer

2) Strings must be compared using equals method:

else if(e.equals("raj"))

Upvotes: 1

PastorPL
PastorPL

Reputation: 1024

Don't use "==" when you compare objects! Change to "equals()" method and should work!

public class Ch2Lu3Ex2
 {
   public static <E> void searchArray(E[] inputArray)
   {
    for(E e : inputArray)
     {
       if(e.equals(30))
         {
          System.out.println("Element found in integer array");
         }
       else if("raj".equals(e)) //This way no null pointer will occure
         {
           System.out.println("Element found in string array");
         }

     }
  } 

 public static void main(String[] args)
  {
       Integer[] integerArray = {10,20,30};
       String[] stringArray = {"robin","raj","ravi"};
       searchArray(integerArray);
       searchArray(stringArray);
    }
  }

Upvotes: 1

assylias
assylias

Reputation: 328568

The problem is that you don't know if e is an Integer or a String, and you can't compare a String with an Integer and vice versa.

One solution would be to pass the sought item to your method too - it could look like this:

public static <E> void searchArray(E[] inputArray, E soughtItem) {
    for (E e : inputArray) {
        if (e.equals(soughtItem)) {
            System.out.println("Element found in integer array");
        }
    }
}

And in your main code:

searchArray(integerArray, 30);
searchArray(stringArray, "raj");

Also note that you should use equals instead of == for equality tests.

Finally, all this has already been written by others:

Set<String> set = new HashSet<String> (stringArray);
if (set.contains("raj")) System.out.println("Found raj");

Upvotes: 3

Related Questions