java - 从各种类型的返回值创建列表

标签 java list

我有一个包含不同领域的类(class)。

public class Temporary
{
   private Integer id;
   private String name;
   private String value;

public Integer getId() {
      return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getValue() {
      return value;
   }

   public void setValue(String value) {
      this.value = value;
   }
}

我正在创建一个测试,但我在创建列表时陷入困境,我需要创建一个列表,但我不知道如何做。

这是我的测试

@Test
   public void samepleList() throws Exception {

      Temporary temp = new Temporary();
      temp.setId(42);
      temp.setName("a");
      temp.setValue("b");
      temp.setId(36);
      temp.setName("c");
      temp.setValue("d");
      temp.setId(42);
      temp.setName("e");
      temp.setValue("f");

      List<Temporary> sampleList = Lists.newArrayList();
      sampleList.add(temp.getId();
      sampleList.add(temp.getName();
      sampleList.add(temp.getValue();

}

我的错误发生在sampleList.add(get.getId),正如它所说的

List 类型中的方法 add(Temporary) 不适用于参数(Integer)。

我该如何修复它并能够将它们放入列表中

最佳答案

您只能将临时对象添加到 List<Temporary> ,不是整数或字符串,或者诸如此类的东西。您需要重新阅读泛型和 Java 集合。

顺便说一句,这没有任何意义:

  Temporary temp = new Temporary(); 
  temp.setId(42);
  temp.setName("a");
  temp.setValue("b");
  temp.setId(36);
  temp.setName("c");
  temp.setValue("d");
  temp.setId(42);
  temp.setName("e");
  temp.setValue("f");

为什么要创建一个临时对象,然后设置字段以便稍后覆盖这些字段?这整件事闻起来很有趣。

也许你想做的是:

List<Temporary> tempList = new ArrayList<>(); // create list

Temporary temp = new Temporary();  // create Temporary object
temp.setId(42);
temp.setName("a");
temp.setValue("b");
tempList.add(temp);  // add it to the list

temp = new Temporary();  // create new Temporary object
temp.setId(36);
temp.setName("c");
temp.setValue("d");
tempList.add(temp);  // add it to the list

temp = new Temporary();  // create new Temporary object
temp.setId(42);
temp.setName("e");
temp.setValue("f");
tempList.add(temp);  // add it to the list

关于java - 从各种类型的返回值创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568640/

相关文章:

java - .cshtml 文件中的 Webstorm Intellisense

android - 具有圆形内边缘的方形布局边框

list - 我如何用 Eager 语言制作一个懒惰的列表?

java - Android:如果 Wifi 打开,则强制打开数据网络。在 GSM 上工作失败 CDMA 设备

java - 我可以使用 Spring Framework 分离 JDBC 读取和写入吗?

python - 显示列表中的每个元素

python - 如果在 Python 中我将一个列表放在一个元组中,我可以安全地更改该列表的内容吗?

Python循环遍历列表并根据条件追加

java - Ant 到 Gradle 转换 : Obfuscation and Jar

java - 在 Java 8 中使用 Collectors.toMap 使用 LIst 映射