包含多个元素类型和多个对象的列表



我需要你帮助以下Java:

我有一个List,它包含不同的对象,每个对象有三个不同的值(String, int, double)。

我想把整型值加1。如何访问列表中对象的int值并将其增加1?

谢谢你的帮助!

我试过这样做:

列表。Set (i, intvalue + 1)

有两个问题。首先,您必须确保在列表中使用的是整数值。如果您尝试在不支持加法的类型上执行加法,那么您将得到一个错误。如果你试图访问列表中不存在的位置,你也会得到一个错误。

然后,要更改Integer值,您需要首先获得要"更改"的项的当前值,然后将1添加到其中,最后,将列表中的旧项替换为具有新值的新项。下面是一个如何完成所有这些的示例,假设您想要将1添加到位置i的对象,仅当该项目存在并且是Integer时:

public static void main(String[] args) {
List<Object> someList = new ArrayList<>();
someList.add("A String");
someList.add(100);
someList.add(100.2);
int i = 1;
if (someList.size() > i) {
Object originalValue = someList.get(i);
if (originalValue instanceof Integer) {
someList.set(i, (Integer)originalValue + 1);
}
}
System.out.println(someList);
}

结果:

[A String, 101, 100.2]

注意,从列表中取出原始值后,必须将其强制转换为Integer。列表必须是Object的列表,因为您希望能够在其中存储多种类型的值。因此,一旦您知道正在处理Integer,就需要显式地将值强制转换为Integer,以便Java将其视为数值。

通过调用list.set(),您可以在前一个对象的位置上放置一个新对象(从列表中删除前一个对象)。

这不是你需要的。你需要让对象访问它的属性。假设您要访问的对象的属性位于索引1。然后这样做:

list.get(1).count++;

,其中count是类型为int的对象的属性名。

假设你有一个名为Pojo的类

class Pojo {
private String str;
private int integerValue;
private double doubleValue;
public Pojo(String str, int integerValue, double doubleValue) {
this.str = str;
this.integerValue = integerValue;
this.doubleValue = doubleValue;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public int getIntegerValue() {
return integerValue;
}
public void setIntegerValue(int integerValue) {
this.integerValue = integerValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
}

现在你有一个Pojo对象列表,其中你想增加整数的值。下面的代码将工作,假设您可以使用setter方法更改/增加值。

public static void main(String[] args) {
Pojo p1 = new Pojo("str1", 1, 1.5);
Pojo p2 = new Pojo("str2", 2, 2.5);
List<Pojo> listOfPojo = Arrays.asList(p1, p2);
List<Pojo> collect = listOfPojo
.stream()
.map(pojo -> pojo.setIntegerValue(pojo.getIntegerValue() + 1))
.collect(Collectors.toList());

}

最新更新