System.out.println(iterator.next().toString());输出的是地址而不是文本
时间: 2024-05-13 13:18:43 浏览: 13
如果你想要输出文本而不是对象地址,需要在调用 `toString()` 方法之前先确认该对象是否重写了 `toString()` 方法。如果该对象没有重写 `toString()` 方法,则默认输出对象的地址。如果你需要输出文本而不是地址,那么你需要在该对象中重写 `toString()` 方法,以便它能够输出你需要的文本信息。例如:
```java
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
```
在上面的例子中,我们重写了 `Person` 类的 `toString()` 方法,使其能够输出该对象的姓名和年龄信息。这样,当你执行 `System.out.println(person.toString());` 时,它将输出类似于 `Person{name='John', age=30}` 的文本信息而不是对象的地址。
相关问题
System.out.println(iterator.next());输出的是地址而不是文本
如果你使用的是Java中的迭代器(Iterator),则默认情况下,它将返回对象的地址而不是文本。要输出文本,你需要使用对象的toString()方法,例如:
```
System.out.println(iterator.next().toString());
```
或者使用Java 8中的forEachRemaining()方法:
```
iterator.forEachRemaining(item -> System.out.println(item.toString()));
```
这将输出迭代器中每个对象的文本。
public class Client{ public static void display(Television tv) { TVIterator i=tv.createIterator(); System.out.println("电视机频道:"); while(!i.isLast()){ System.out.println(i.currentChannel().toString()); i.next(); } } public static void reverseDisplay(Television tv){ TVIterator i=tv.createIterator(); i.setChannel(5); System.out.println("逆向遍历电视机频道:"); while(!i.isFirst()) { i.previous(); System.out.println(i.currentChannel().toString()); } } public static void main(String a[]){ Television tv; tv = (Television)XMLUtil.getBean(); display(tv); System.out.println("--------------------------"); reverseDisplay(tv); } }
这段代码是一个迭代器模式的实现例子,其中包括一个Client类和一个Television类,Television类实现了Iterator接口,Client类通过Television类的createIterator方法获取到TVIterator对象,然后通过遍历TVIterator对象来打印电视机频道。其中,reverseDisplay方法实现了逆向遍历电视机频道的功能。通过XMLUtil.getBean方法获取到的Television对象可能是不同的具体子类对象,这样可以动态地改变电视机频道的实现方式。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)