2016-07-18 37 views
-1

我是新的泛型,我有一個創建泛型類的數組的問題。在JAVA中的泛型類的數組

如果我有一個,我想創建一個單獨的主要在同一個Java項目通用數組至極回答兩個不同類型字符串和整數。

我可以把兩個difreent類型相同的數組?

,是它確定調用主這樣的:

public static <T> void main(String[] args) { 

    String name; 
    int grade; 
    int choice; 
    int count = 0; 
    String number; 

    System.out.println("press 1 if you like to save id as integer ,or press 2 to for a string "); 
    choice = s.nextInt(); 

    Student<T>[] array = new Student[NUM_OF_STUDENTS]; 

    if (choice == 1) { 

     System.out.println("please enter student name :"); 
     s.nextLine(); 
     name = s.nextLine(); 

     while (!name.isEmpty() && count != NUM_OF_STUDENTS) { 
      System.out.println("please enter student #" + (count + 1) + " grade :"); 
      grade = s.nextInt(); 
      array[count] = new Student(count + 1, name, grade); 
      count++; 
      ... 

....

+1

爲什麼學生甚至是通用的?泛型允許你做什麼? –

+0

班學生是通用的,因爲它允許將學生ID作爲整數或字符串添加爲用戶請求。 – dan

+0

在這種情況下,一個更簡單的解決方案是將其另存爲一個字符串,但具有解析該id的'''getAsInt'''方法。 (但你可能這樣做是爲了學習...) –

回答

-1

According to Oracle,沒有你不能有泛型陣列。

PS:你忘了初始化小號,這我假設是java.util.Scanner中

Scanner s = new Scanner(System.in); 

也不要做:

System.out.println("please enter student name :"); 
s.nextLine(); 
name=s.nextLine() 

只是做:

System.out.println("please enter student name :"); 
name=s.nextLine() 

Otherwis e s.nextLine()跳過一行。

+0

需要浮動's.nextLine()'。 –

+1

'public static void main(String [] args){...}'編譯並運行正常。這沒有用,但它是合法的。不要忘記,JVM只能看到方法的擦除,這與'public static void main(String [] args)''相同。 –

+0

另外,'String ... args'也是合法的。 –