หน้าเว็บ

วันพุธที่ 15 สิงหาคม พ.ศ. 2555

generic method java

Interface
package com.blogspot.na5cent.prototype;

/**
 *
 * @author redcrow
 */
public interface Model{
    public Integer getId();
    public void setId(Integer id);
}
Implementation
package com.blogspot.na5cent.model;

import com.blogspot.na5cent.prototye.Model;

/**
 *
 * @author redcrow
 */
public class User implements Model{
    private Integer id;

    public Integer getId(){
        return id;
    }

    public void setId(Integer id){
        this.id = id;
    }
}
Library
package com.blogspot.na5cent.library;

import java.util.List;
import com.blogspot.na5cent.prototye.Model;

/**
 *
 * @author redcrow
 */
public class FindObject {

    public static <T extends Model> T findById(Integer id, List<T> list) {
        int size = list.size();
        int last = size - 1;
        if (size == 0) {
            return null;
        }
        
        //binary search
        for (int i = 0; i < size; i++) {
            //first to last
            if (list.get(i).getId().equals(id)) {
                return list.get(i);
            }

            //last to first
            if (list.get(last - i).getId().equals(id)) {
                return list.get(last - i);
            }
        }
        return null;
    }
}
Using
package com.blogspot.na5cent;

import java.util.List;
import com.blogspot.na5cent.library.FindObject;
...
...

List<User> uers;
Integer id;
...
...
...
User findUser = FindObject.findById(id, users); 
...
...

ไม่มีความคิดเห็น:

แสดงความคิดเห็น