Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
arraylist的内容使用println打印。我希望为我创建的对象提供类似的功能,而不必在java中使用toString()函数_Java_Oop_Object_Arraylist_Tostring - Fatal编程技术网

arraylist的内容使用println打印。我希望为我创建的对象提供类似的功能,而不必在java中使用toString()函数

arraylist的内容使用println打印。我希望为我创建的对象提供类似的功能,而不必在java中使用toString()函数,java,oop,object,arraylist,tostring,Java,Oop,Object,Arraylist,Tostring,在上图中,使用println打印arraylist的内容。我希望为我创建的对象提供类似的功能,而不必在java中使用toString()函数 请告诉我如何做为了方便回答,我添加了一个带有toString方法的CustomClazz和两个要打印的字段(firstField,secondField)。代码使用每个对象的toString方法和Stream->println import java.util.ArrayList; 导入java.util.array; 公共类MyClass{ 公共静态vo

在上图中,使用println打印arraylist的内容。我希望为我创建的对象提供类似的功能,而不必在java中使用toString()函数
请告诉我如何做

为了方便回答,我添加了一个带有toString方法的CustomClazz和两个要打印的字段(firstField,secondField)。代码使用每个对象的
toString
方法和Stream->println

import java.util.ArrayList;
导入java.util.array;
公共类MyClass{
公共静态void main(字符串参数[]){
ArrayList=新建ArrayList();
添加(新的CustomClazz(“custom1”、“class1”);
添加(新的CustomClazz(“custom2”、“class2”));
添加(新的CustomClazz(“custom3”、“class3”));
//访问和连接自定义类的每个字段的流。请注意错误的连接“+”
list.stream().map(customClass->customClass.getFirstField()+customClass.getSecondField()).forEach(System.out::println);
System.out.println();
System.out.println();
//使用customClazz的toString方法的选项。
System.out.println(Arrays.toString(list.toArray());
}
}
类CustomClazz{
字符串firstField;
@凌驾
公共字符串toString(){
返回“CustomClazz{”+
“firstField='”+firstField+'\''+
,secondField='“+secondField+'\'”+
'}';
}
字符串字段;
公共字符串getFirstField(){
返回第一个字段;
}
public void setFirstField(字符串firstField){
this.firstField=firstField;
}
公共字符串getSecondField(){
返回第二个字段;
}
public void setSecondField(字符串secondField){
this.secondField=secondField;
}
公共CustomClazz(字符串第一个字段,字符串第二个字段){
超级();
this.firstField=firstField;
this.secondField=secondField;
}
}

当您说不使用toString()时,您的意思是不在对象中调用方法.toString()?我没有理解您的问题。您的意思是在ArrayList中存储对象而不是整数或字符串值吗?您必须将toString()方法重写到自定义对象中为什么不重写toString()?添加了一个实现,该实现不对customClass.list.stream().map(customClass->customClass.getFirstField()+customClass.getSecondField())使用toString。forEach(System.out::println);您能更详细地解释一下这一行吗?这将非常有助于解释此链接中的
stream.map
。然后“customClass”是当前对象..然后将第一个字段和第二个字段连接起来..然后将从stream.map print out创建的映射的每个元素打印到sys out