[Turn] java Summary: Generic

Reference java generics operations review and explain the use of the android scene in
Java summary article series: Java generics
java generics and array

using generic android many places, such as integrated package from Adapter BaseAdapter achieved, operation of the common package, but the need for processing incoming data transmission, on the use of the generic case, the following example:

public abstract class EasyAdapter<T> extends BaseAdapter {
    private LayoutInflater inflater;
    private int layoutId;
    private List<T> mlist = new ArrayList<T>();

    public EasyAdapter(Context context, int layoutId, List<T> list) {
        super();
        this.inflater = LayoutInflater.from(context);
        this.layoutId = layoutId;
        this.mlist = list;
    }

    /**
     * 往顶部添加数据
     * 
     * @param list
     */
    public void add2Head(List<T> list) {
        mlist.addAll(0, list);
        notifyDataSetChanged();
    }
    
    public void clearAll() {
        mlist.clear();
        notifyDataSetChanged();
    }

    public List<T> getAllList() {
        return mlist;
    }

    /**
     * 往底部添加数据
     * 
     * @param list
     */
    public void add2Bottom(List<T> list) {
        mlist.addAll(list);
        notifyDataSetChanged();
    }

    public void add2Bottom(T t) {
        mlist.add(t);
        notifyDataSetChanged();
    }

    /**
     * @Title: updateListView
     * @Description: TODO(更新BaseAdapter中的数据)
     * @param @param list 设定文件
     * @return void 返回类型
     * @throws
     */
    public void updateListView(List<T> list) {
        mlist = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mlist.size();
    }

    @Override
    public T getItem(int position) {
        return mlist.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    /**
     * 实际显示View的方法,使用抽象方法强制调用者覆写!
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = ViewHolder.getViewHolder(parent, convertView,
                inflater, layoutId);
        convert(viewHolder, mlist.get(position));
        return viewHolder.getConvertView();

    }

    public abstract void convert(ViewHolder viewHolder, T t);

}

As also used to parse json Gson data, data corresponding to the bean json entity class are different:

public class GsonImpl extends Json {
    private Gson gson = new Gson();

    @Override
    public String toJson(Object src) {
        return gson.toJson(src);
    }

    @Override
    public <T> T toObject(String json, Class<T> claxx) {
        return gson.fromJson(json, claxx);
    }

    @Override
    public <T> T toObject(byte[] bytes, Class<T> claxx) {
        return gson.fromJson(new String(bytes), claxx);
    }

    @Override
    public <T> List<T> toList(String json, Class<T> claxx) {
          Type type = new TypeToken<ArrayList<T>>() {}.getType();  
             List<T> list = gson.fromJson(json, type);  
        return list;
    }

}

What is a generic?

Generic, or "parameterized types." Mention of parameters, the most familiar with is visible when defining method parameters, and then call this method when passing arguments. So how to understand parameterized type it? As the name suggests, is a specific type as a parameter of the original, similar to the process variable parameter types are also defined at this time in the form of parameters (type parameter may be referred to), and particularly when using the incoming / calling type (type arguments).

For chestnut:

public class GenericTest {

    public static void main(String[] args) {
       
        List<String> list = new ArrayList<String>();
        list.add("qq");
        list.add("im");
        //list.add(100);   // 1  提示编译错误

        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i); // 2
            System.out.println("name:" + name);
        }
    }
}

After compilation error occurs when using generic wording, at 1 // Integer want to add a type of the object, by List, it defines the list directly set contains only elements of type String, eliminating the need for forced at // 2 type conversion, because at this time, the set can remember the type of information element, the compiler has been able to confirm that it is the type String.

Combined with the generic definition of the above, we know that in the List, String is the type of argument, that is, the corresponding List interface certainly contain a type parameter. And returns a result get () method is also directly This parameter types (i.e. corresponding to the type of arguments passed).

java foundation of knowledge about generics:

First of all: Generics are the new features java1.5 provided; mainly to solve the data type of security problem, it is when the class declaration marked by a class that represents the type of a property or a method's return value and Parameter Type. So as long as you need to specify the type in the class declaration or instantiation.

Generic defined as follows:
Here Insert Picture Description
Actual use:
Here Insert Picture Description
to better protect the data type, the compiler to avoid an error. Reduce the code type conversion.

Of course, a value can be passed by providing generic operation parameters for the generic method of construction.

Generic safety warning:
Here Insert Picture Description

Tsuhaifu

In passing reference to the development of an object is the most common, but in a generic operation, performed when referring to the generic must pass before they can match the transfer, otherwise can not be delivered

class Info<T>{
    private T var ;        // 定义泛型变量
    public void setVar(T var){
        this.var = var ;
    }
    public T getVar(){
        return this.var ;
    }
    public String toString(){    // 直接打印
        return this.var.toString() ;
    }
};
public class GenericsDemo14{
    public static void main(String args[]){
        Info<String> i = new Info<String>() ;        // 使用String为泛型类型
        i.setVar("MLDN") ;                            // 设置内容
        fun(i) ;
    }
    public static void fun(Info<?> temp){        // 可以接收任意的泛型对象
        System.out.println("内容:" + temp) ;
    }
};

use? You can accept any type of data, but can not be modified? It is the wildcard

Generic limited

Here Insert Picture Description

Generics and array

java, arrays are not supported by generics, because:

Generic only at compile time, play type detection, and generates a byte code type conversion, i.e. having a generic java file finally generated bytecode will erase the generic information, the specific reference data object type are generally used to replace. And adding the conversion code corresponding to the type of location.

Java array specified instantiation needs to know exactly what type of data (an operation which is more convenient to use an array) storage. That is assumed to support generic array, then for T [] = new T [10] when compiled into bytecode; eventually translated into Object [] objects = new Object [10], that is to say the specific array during operation type is the type of object, this time for the operation of the elements within an array may also be used normally strong rotation. However the compiler generates byte code is also possible to generate the time (String []) (Objects) such strong rotation codes (conversion error)

Wrapper class generic array:

Examples of an object using an array of array of a generic indirectly:
GenericArray.java

public class GenericArray<T> {
    private Object[] values;

    public GenericArray(int count){

        values = new Object[count];

    }

    public void setValue(T t,int position){

        values[position] = t;
    }

    public T getValue(int position){

        return (T)values[position];
    }

    //注意此句代码调用会出错
    public T[] getValues(){

        return (T[])values;
    }
}

Test code:

public class Test {

    public static void main(String[] args) {

        GenericArray<String> generic=new GenericArray(10);

        generic.setValue("wenwei1", 0);
        generic.setValue("wenwei2", 1);

        System.out.println(generic.getValue(0));
        System.out.println(generic.getValue(1));
        //
        String[]content = generic.getValues();
        }
    }

The results:
Here Insert Picture Description
Analysis: The above code compiler, and we use stored data GenericArray normal use, but we will call its getValues strongly turn type errors (this is an error in the summary of our analysis appear in the compiler to generate a strong rotation Code caused).

Example 2 using a generic array type identifier indirectly:
GenericArray1.java

public class GenericArray1 <T>{
    private T[] values;

    public GenericArray1(Class<T> type,int length){
        values= (T[])Array.newInstance(type, length);
    }

    public void setValue(T t,int position){

        values[position] = t;
    }

    public T getValue(int position){

        return (T)values[position];
    }

    public T[] getValues(){

        return values;
    }


}

Test code:

public class Test {

    public static void main(String[] args) {

        GenericArray1<String> generic=new GenericArray1<String>(String.class,10);

        generic.setValue("wenwei1", 0);
        generic.setValue("wenwei2", 1);

        System.out.println(generic.getValue(0));
        System.out.println(generic.getValue(1));

        String[]content = generic.getValues();
        System.out.println(content[0]);
        }
    }   

The result:
Here Insert Picture Description
Analysis: the above code can be compiled through, we use GenericArray store data can be used normally, but will not be strong call to turn its getValues type of error, this way more recommended (as we call Array.newInstance () resulting array is String [] array type).

Additional information: For generic array, the simplest we can achieve using the container to simulate List!

Guess you like

Origin blog.csdn.net/weixin_43115440/article/details/90607736