I now need is : to define a type A, can be assigned to almost any type A, I can pass as a result of the A to another place, and then type in other places and then convert it back - using casts - use it. I put this A set Object, String pass when there is no problem , place the receiver using casts (String). But ran into a HashMap , compile time warning , though does not affect operation. I would like to use a program without warning .
Can generics do not know , T, V , etc. What does it mean , what's the difference ? ------ Solution ---------------------------------------- ---- this warning can not be avoided , the parent wants to turn into any subclass will have this warning , as long as you get to know your way what type will ensure the program is running will not throw ClassCastException on the line. ------ Solution ---------------------------------------- ---- after receiving how to use it ? Object.? I want to pass HashMap !
directly set to take the time to go get on the line ah you tried it?
import java.util.HashMap;
public class NewMainTest<T> {
private T obj;
public void setObj(T obj) { this.obj = obj; }
public T getObj() { return obj; }
/** * @param jsonArray the command line arguments */ public static void main(String args[]) throws Exception { NewMainTest nmt = new NewMainTest<>(); HashMap<String, String> map = new HashMap<>(); nmt.setObj(map); HashMap<String, String> map1 = (HashMap<String, String>) nmt.getObj(); //map1.get; } }
warning ah.
it will only add a comment how to add a comment ? @ SuppressWarnings ("unchecked") can be added to the front line of code , only the line of work , ah, easy to use !
ah see SuppressWarnings target range @ Target (value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) anything can be added in addition to the front of the package and annotation ------ For reference only ----------------------- ----------------
public class A<T> { private T obj;
public void setObj(T obj) { this.obj = obj; }
public T getObj() { return obj; }
}
requires you to specify certain generic type , if you want to be able to pass any object A is necessary to specify the generic Object, for example : A
没有评论:
发表评论