在(Java)中实现toString()方法时遇到问题
我正在编写一个使用两个不同类的程序。一个类包含main方法,另一个类是泛型类集,该泛型类集具有一组使用ArrayList的泛型类型T的项 此程序查找两个集合的交集 我想使用toString()方法,但我不知道在数据字段不可见的特定情况下如何实现它在(Java)中实现toString()方法时遇到问题,java,tostring,Java,Tostring,我正在编写一个使用两个不同类的程序。一个类包含main方法,另一个类是泛型类集,该泛型类集具有一组使用ArrayList的泛型类型T的项 此程序查找两个集合的交集 我想使用toString()方法,但我不知道在数据字段不可见的特定情况下如何实现它 import java.util.Random; //Generic class Set<T> class Set <T> { ArrayList<T> num = new ArrayList<T&
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());
}
}
import java.util.Random;
//泛型类集
类集
{
ArrayList num=新的ArrayList();
/*在这个类中,我有(1)一个add方法,(2)一个remove方法,
(3)如果项在集合中,则返回true的方法,并且
如果不在集合中,则为false*/
//这是交叉法
公共静态集合交叉点(集合k,集合p){
集合abc=新集合();
/*我这里有一些其他代码来找到交叉点
两套不同的*/
返回abc;
}
@凌驾
/*这就是我完全迷路的地方
我不知道如何使用这种方法来打印
两个集合的交集*/
公共字符串toString(){
/*我不知道在这里执行什么才能返回
表示当前对象的字符串*/
回来
}
}
公务舱二等舱{
//主要方法
公共静态void main(字符串[]args){
/*这个程序生成随机数
为了找到
两个集合的交集*/
Set firstSet=新集合();
Set secondSet=新集合();
集合结果=新集合();
结果=集合交点(第一集合、第二集合);
//显示交叉口?
System.out.println(result.toString());
}
}
您似乎正在使用阵列列表作为支持数据结构。它有一个实现良好的toString()
,为什么不直接委托给它呢
@Override public String toString() { return num.toString(); }
请注意,已经有一个名为Set
:java.util.Set
的标准接口。将自己的类命名为标准Java库中的某个类并不是一个好主意,这可能会导致错误消息混淆。将类重命名为非Set
。这取决于您希望对象的字符串表示形式的外观。没有一个正确的答案,尽管我想指出ToStand不应该用来控制逻辑流(例如通过识别/比较对象),所以如果这是你的目标-不要:-你指的是“当数据字段不可见”?@ LycC还有另一个有效的选项要考虑吗?使用对象字段/方法来处理它。Implement equals()要进行比较,请实现用于所需特定比较的方法。只是不要用toString来控制你的逻辑,否则你可能会玩得不开心。