您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)Java中怎么創(chuàng)建一個(gè)泛型數(shù)組,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。
在java中,不能通過(guò)直接通過(guò)T[] tarr=new T[10]的方式來(lái)創(chuàng)建數(shù)組,最簡(jiǎn)單的方式便是通過(guò)Array.newInstance(Class<t>type,int size)的方式來(lái)創(chuàng)建數(shù)組例如下面的程序。
public class ArrayMaker<T> { private Class<T> type; public ArrayMaker(Class<T> type) { this.type = type; } @SuppressWarnings("unchecked") T[] createArray(int size) { return (T[]) Array.newInstance(type, size); } List<T> createList() { return new ArrayList<T>(); } /** * @param args */ public static void main(String[] args) { /* * Even though kind is stored as Class<T> , erasure means that it is actually just being stored as a Class, with * no parameter. So, when you do some thing with it, as in creating an array, Array.newInstance( ) doesn’t * actually have the type information that’s implied in kind; so it cannot produce the specific result, wh ich * must therefore be cast, which produces a warning that you cannot satisfy. */ ArrayMaker<Type> am2 = new ArrayMaker<Type>(Type.class); System.out.println(Arrays.asList(am2.createArray(10))); System.out.println(Arrays.asList(am2.createList())); } } class Type { @Override public String toString() { return "type"; } }
上面的這個(gè)例子比較簡(jiǎn)單,但是如果你有接觸過(guò)泛型數(shù)組,你便對(duì)他的復(fù)雜度有一定的了解,由于創(chuàng)建泛型數(shù)組比較復(fù)雜,所以在實(shí)際的應(yīng)用過(guò)程中一般會(huì)選擇List的對(duì)泛型進(jìn)行存儲(chǔ),如果實(shí)在需要使用泛型數(shù)組,則需要注意數(shù)組的在運(yùn)行時(shí)的類型,think in java這本書(shū)中,對(duì)泛型數(shù)組的處理通過(guò)四個(gè)小程序?qū)ζ溥M(jìn)行了比較完整的描述。
程序一:這個(gè)程序主要說(shuō)明了,在使用泛型數(shù)組中容易出現(xiàn)的問(wèn)題,由于書(shū)中對(duì)于程序的說(shuō)明比較詳細(xì),所以只對(duì)程序做引用。
class Generic<T> { } public class ArrayofGeneric { public static void main(String[] args) { Generic<Integer>[] genArr; /* * will throw ClassCastException :The problem is that arrays keep track of their actual type, and that type is * established at the point of creation of the array. So even though genArr has been cast to a Generic < Integer * >[] , that information only exists at compile time (and without the @SuppressWarnings annotation, you’d get a * warning for that cast). At run time, it’s still an array of Object, and that causes problems. */ // genArr = (Generic<Integer>[]) new Object[] {}; /* can not create a generic of array */ // genArr=new Generic<Integer>[2]; genArr = (Generic<Integer>[]) new Generic[2]; System.out.println(genArr); } }
程序二:這個(gè)程序主要是說(shuō)明在程序的執(zhí)行過(guò)程中,泛型數(shù)組的類型信息會(huì)被擦除,且在運(yùn)行的過(guò)程中數(shù)組的類型有且僅有Object[],如果我們強(qiáng)制轉(zhuǎn)換成T[]類型的話,雖然在編譯的時(shí)候不會(huì)有異常產(chǎn)生,但是運(yùn)行時(shí)會(huì)有ClassCastException拋出。
/** * * Because of erasure, the runtime type of the array can only be Object[]. If we immediately cast it to T[], then at * compile time the actual type of the array is lost, and the compiler may miss out on some potential error checks. * * * * archive $ProjectName: $ * * @author Admin * * @version $Revision: $ $Name: $ */ public class ArrayOfGeneric2<T> { public T[] ts; public ArrayOfGeneric2(int size) { ts = (T[]) new Object[size]; } public T get(int index) { return ts[index]; } public T[] rep() { return ts; } public void set(int index, T t) { ts[index] = t; } public static void main(String[] args) { ArrayOfGeneric2<String> aog2 = new ArrayOfGeneric2<String>(10); Object[] objs = aog2.rep(); System.out.println(objs); /* will throw ClassCastException */ // String[] strs = aog2.rep(); // System.out.println(strs); } }
程序三:主要說(shuō)明在對(duì)象中通過(guò)用Object[]來(lái)保存數(shù)據(jù),則生成對(duì)象是,可以對(duì)其持有的對(duì)象在T和object之間進(jìn)行轉(zhuǎn)換,但是當(dāng)設(shè)計(jì)到數(shù)組的轉(zhuǎn)換時(shí),還是會(huì)報(bào)ClassCastException
/** * * Initially, this doesn’t look very different compare with ArrayOfGeneric2.java , just that the cast has been moved. * Without the ©SuppressWarnings annotations, you will still get "unchecked" warnings. However, the internal * representation is now Object[] rather than T[]. When get( ) is called, it casts the object to T, which is in fact the * correct type, so that is safe. However, if you call rep( ) , it again attempts to cast the Object[] to a T[], which * is still incorrect, and produces a warning at compile time and an exception at run time. Thus there’s no way to * subvert the type of the underlying array, which can only be Object[]. The advantage of treating array internally as * Object[] instead of T[] is that it’s less likely that you’ll forget the runtime type of the array and accidentally * introduce a bug (although the majority, and perhaps all, of such bugs would be rapidly detected at run time) * * * * archive $ProjectName: $ * * @author Admin * * @version $Revision: $ $Name: $ */ public class ArrayOfGeneric3<T> { Object[] ts; public ArrayOfGeneric3(int size) { ts = new Object[size]; } public T get(int index) { return (T) ts[index]; } public T[] rep() { return (T[]) ts; } public void set(int index, T t) { ts[index] = t; } public static void main(String[] args) { ArrayOfGeneric3<Integer> aog2 = new ArrayOfGeneric3<Integer>(10); Object[] objs = aog2.rep(); for (int i = 0; i < 10; i++) { aog2.set(i, i); System.out.println(aog2.get(i)); } Integer[] strs = aog2.rep(); System.out.println(strs); } }
程序四:是對(duì)泛型數(shù)組相對(duì)而言比較***的解決方案
/** * * The type token Class<T> is passed into the constructor in order to recover from the erasure, so that we can create * the actual type of array that we need, although the warning from the cast must be suppressed with @SuppressWarnings. * Once we do get the actual type, we can return it and get the desired results, as you see in main( ). The runtime type * of the array is the exact type T[]. * * @author Admin * * @version $Revision: $ $Name: $ */ public class ArrayOfGeneric4<T> { T[] ts; public ArrayOfGeneric4(Class<T> type, int size) { /* to solution array of generic key code! */ ts = (T[]) Array.newInstance(type, size); } public T get(int index) { return ts[index]; } public T[] rep() { return ts; } public void set(int index, T t) { ts[index] = t; } public static void main(String[] args) { ArrayOfGeneric4<Integer> aog2 = new ArrayOfGeneric4<Integer>(Integer.class, 10); Object[] objs = aog2.rep(); for (int i = 0; i < 10; i++) { aog2.set(i, i); System.out.println(aog2.get(i)); } try { Integer[] strs = aog2.rep(); System.out.println("user Array.newInstance to create generci of array was successful!!!!! "); } catch (Exception ex) { ex.printStackTrace(); } } }
以上就是Java中怎么創(chuàng)建一個(gè)泛型數(shù)組,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。