Results 1 to 3 of 3
  1. #1
    Manddd is offline Member
    Join Date
    Mar 2015
    Posts
    23
    Rep Power
    0

    Default Question about a generic method

    So I have to create a method that takes 2 arguments ( one an array, the other an element) and then verifies if the element is in the array. However an error in eclipse and don't know how to solve it...
    Java Code:
    package qu2;
    
    public class gen<E> {
    
    	public void  test(E[] ob, E obj){
    		for(int i = 0; i<ob.length; i ++){
    			if(obj.getClass() == ob[i]);
    				System.out.println("Obj at index " + i + "is in the array");
    		}
    	}
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		String[] str = {"mine", "yours", "minetoo"};
    		String yours = "mine";
    		test(str, yours); // ERROR IS HERE
    	}
    
    }
    Eclipse says "The method test(E[], E) in the type gen<E> is not applicable for the arguments (String[], String)"

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    26

    Default Re: Question about a generic method

    The real issue is that you're trying to access a non-static method from the static context of a main(..) method.

    Unless you're specifically tasked to reinvent the wheel, the goal can be achieved using Arrays#asList(...) and List#contains(...) or by using Arrays#sort(...) and Arrays#binarySort(...).

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Question about a generic method

    You have other problems too.

    1. A semi colon after the if statement.
    2. Comparing the class of the object to the object (you probably want to use equals here anyway, not == for string comparisons).

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Generic Type Question
    By Firen4000 in forum Advanced Java
    Replies: 3
    Last Post: 07-12-2012, 11:31 PM
  2. About generic, cant use method
    By oszc in forum New To Java
    Replies: 4
    Last Post: 09-13-2011, 06:35 PM
  3. Question about generic parameters
    By Dirty Protest in forum New To Java
    Replies: 3
    Last Post: 07-01-2011, 06:19 AM
  4. Generic Question
    By kwgivler in forum New To Java
    Replies: 5
    Last Post: 03-10-2011, 10:50 PM
  5. Generic method
    By jomypgeorge in forum New To Java
    Replies: 6
    Last Post: 01-18-2011, 05:51 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •