我正在编写一个使用两个不同类的程序。一个类包含main方法,另一个类是泛型类Set,它具有一组使用ArrayList的泛型类型T的项。
该程序找到两组的交集。
我想使用toString()方法,但是当数据字段不可见时,我不知道如何在这种特定情况下实现它。
import java.util.Random;
//Generic class Set<T>
class Set <T>
{
ArrayList<T> num = new ArrayList<T>();
/*Within this class I have (1) an add method, (2) a remove method,
and (3) a method that returns true if the item is in the set and
false if it is not in the set*/
//This is the intersection method
public static <T> Set<T> intersection(Set<T> k, Set<T> p){
Set<T> abc = new Set<T> ();
/*I have some other codes here to find the intersection
of two different sets*/
return abc;
}
@Override
/*Here is where I am completely lost
I do not know how to use this method in order to print
out the intersection of both sets*/
public String toString() {
/*I don't know what to implement here in order to return
a string that represents the current object*/
return;
}
}
public class SecondClass {
//MAIN METHOD
public static void main(String [] args){
/* This program generates random numbers
for two sets in order to find the
intersection of both sets. */
Set<Integer> firstSet = new Set<Integer>();
Set<Integer> secondSet = new Set<Integer>();
Set<Integer> result = new Set<Integer>();
result = Set.intersection(firstSet,secondSet);
//Display intersection?
System.out.println(result.toString());
}
}
答案 0 :(得分:2)
您似乎使用ArrayList
作为支持数据结构。它有一个很好实现的toString()
,那么为什么不直接委托给它呢?
@Override public String toString() { return num.toString(); }