2014-10-10 36 views
3

我創建了一個返回兩組值的交集的方法。問題是我想使用一個不同的簽名,它只在方法中使用一個arrayList,而不是全部。返回兩組交集的不同簽名的方法(Java)

public class Group <T> 
{  
    ArrayList<T> w = new ArrayList<T>(); 

    //Here I have the add and remove methods and a method that returns 
    //false if the item is not in the set and true if it is in the set 

    public static ArrayList intersection(Group A, Group B) 
    { 
    ArrayList list = new ArrayList(); 
    ArrayList first = (ArrayList) A.w.clone(); 
    ArrayList second = (ArrayList) B.w.clone(); 


    for (int i = 0; i < A.w.size(); i++) 
    { 
     if (second.contains(A.w.get(i))) 
     { 
      list.add(A.w.get(i)); 
      second.remove(A.w.get(i)); 
      first.remove(A.w.get(i)); 
     } 
    } 
    return list; 
    } 
} 

這是具有不同簽名的另一種方法。如果簽名與上面顯示的方法不同,如何使此方法返回兩個集合的交集?

public class Group <T> 
{ 
    ArrayList<T> w = new ArrayList<T>(); 

    public static <T> Group<T> intersection(Group <T> A, Group <T> B) 
    { 
     Group<T> k= new Group<T>(); 


    return k; 
    } 
} 

public class Main 
{ 
    public static void main(String [] args) 
    { 
     Group<Integer> a1 = new Group<Integer>(); 
     Group<Integer> b1 = new Group<Integer>(); 
     Group<Integer> a1b1 = new Group<Integer>(); 


     //Here I have more codes for input/output 
     } 
} 
+0

您不應該使用原始類型,參數'A'和'B'應該是小寫。 – 2014-10-10 20:52:17

回答

3

您不能通過在Java中返回值來重載方法 - 您必須重命名它們中的一個。例如:

public static <T> Group<T> intersectionGroup(Group <T> A, Group <T> B) 

public static ArrayList intersectionArrayList(Group A, Group B) 
+0

我不打算整合這兩種方法。我只想知道如何創建一個具有不同簽名的類似方法。 – Plrr 2014-10-10 20:50:38

+0

@Plrr我認爲他回答了你 - 你不能。不是你想要這樣做的方式。這在Java中是不合法的。抱歉。 – ajb 2014-10-10 21:00:45

+0

@ajb Java中的「非法」究竟是什麼? – Plrr 2014-10-10 21:26:03

相關問題