[英]How can I pass an array as an argument to a function, as well as an object of the same data type of those stored in the array?
我想制作一個 function ,它采用一個數組和一個 object 作為其 arguments:
public static int myFunction(Object[] array, Object obj) {
//Stuff
}
但是,我想確保obj
的數據類型與存儲在array
中的數據類型相同。 如果它們不一樣,我可以通過僅使用obj instanceof array[0]
來拋出異常,但我很好奇是否有辦法在 function 的 arguments 中指定它。 我懷疑 generics 可能有辦法做到這一點,但我對他們的經驗還不夠確定。 任何幫助深表感謝!
如果要編譯時檢查,可以使用 Generics:
public static <T> int myFunction(T[] array, T obj) {
//Stuff
}
You can read up a bit more on Generic Methods in the Java docs: https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
只需測試 class 是否相等
public class Program {
public static void main(String[] args) {
Object[] arr = new Object[3];
arr[0] = "akflj";
char test1 = 'a';
String test2 = "azdf";
System.out.println(test(arr, test1));
System.out.println(test(arr, test2));
}
public static boolean test(Object[] arr, Object item) {
if(item.getClass().equals(arr[0].getClass())) {
return true;
}
return false;
}
}
只有當一個項目已經在數組中時才能正常工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.