2014-10-10 58 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