Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How created method with signature as List

I'm very new to Java programming language so this is probably dumb question but I have to ask it because I can't figure it out on my own. Here is the deal.

I want to create method which extracts certain object type from a list. So the method should receive List as argument, meaning list should contain either Object1 or Object2. I've tried like this :

   public Object1 extractObject(List<Object>){
    //some pseudo-code 
   ... loop trough list and check if list item is instance of object one return that instance
    }

The problem with declaring method with List<?> as method argument is that I receive compilation error from eclipse Syntax error on token ">", VariableDeclaratorId expected after this token.

How do I set the method signature properly to accept object types either Object1 or Object2 ? Thank you

This is my Code :

protected Object1 getObject1(List<Object> list){
        for(Object obj : list) {
            if(obj instanceof Object1) {
                return (Object1) obj;
            }
        }
        return null;
    }

Edit - what is the difference between these 2 :

public Object1 getObject1(List<Object> list){
        for(Object obj : list) {
            if(obj instanceof Object1) {
                return (Object1) obj;
            }
        }
        return null;
    }

public Object1 extractObject(List<Object> list, Class<Object1> type) {
    for(Object obj : list) {
        if(type.isInstance(obj)) {
            return (Object1)obj;
        }
    }
    return null; // no match found
}
like image 797
London Avatar asked May 17 '10 14:05

London


2 Answers

public Object1 extractObject(List<?> list){
    //some pseudo-code 
   ... loop trough list and check if list item is instance of object one return that instance
    return null;
}

You need a variable for your instance

And a return.

like image 52
Michael B. Avatar answered Sep 21 '22 17:09

Michael B.


I'd do something like this - note, my syntax might be wrong, but the idea is the same.

// this works for any type - just pass in an Object1
public Object extractObject(List<?> list, Class clazz) {
    for(Object obj : list) {
        if(obj.getClass().equals(clazz) {
            return obj;
        }
    }
    return null; // no match found
}

And non-generic:

// this works for just one type
public Object1 extractObject(List<?> list) {
    for(Object obj : list) {
        if(obj.getClass().equals(Object1) {
            return obj;
        }
    }
    return null; // no match found
}

Tested the concepts with this driver:

public static void main(String[] args) {
    Class c = "".getClass();
    if("".getClass().equals(c)) System.out.println("true");
    else System.out.println("false");
}

From the comments, consider clazz.isAssignableFrom(otherClazz) as well.

like image 21
corsiKa Avatar answered Sep 24 '22 17:09

corsiKa