【问题标题】:Java - Change an specific member of an object ArrayListJava - 更改对象 ArrayList 的特定成员
【发布时间】:2021-11-11 17:35:21
【问题描述】:

(我是初学者,所以如果我说错了,请纠正我) 我从不同的对象制作了一个 ArrayList。但我不知道如何更改 ArrayList 上的特定对象。例如,在下面的示例中将人口从 80 更改为 85。 承包商:

class constructor {
  private Contry contry;
  private BigDecimal population;
  private String capital ;

  public constructor(Contry contry, BigDecimal population, String capital){

    this.contry = contry;
    this.population = population;
    this.capital = capital;
  }

和我的方法:

public class ContryInfo {
  public List<constructor> information(Contry contry, BigDecimal population,
      String capital) {
    List<constructor> contriesInfo = new ArrayList<>();
    contriesInfo.add(new constructor(contry, population, capital));
return Information

和我的主要

public static void main(String[] args) {
    List<constructor> exampleList = new ArrayList<>();
    exampleList = new ContryInfo().Information(Germany, new BigDecimal("80"), "Berlin");

我尝试使用 stream().map 但没有成功找到方法。如果你们写出我的问题的解决方案,我会很高兴。

【问题讨论】:

  • 在尝试此操作之前,您应该学习有关 Java 基础知识的教程或教科书。您不了解构造方法的基础知识,也不了解基本的 Java 命名约定。对这个网站来说不是一个好问题。

标签: java object arraylist stream set


【解决方案1】:

首先,您必须 A) 添加 setter 来更改变量的值,或者 B) 将它们作为 public 来作为可见变量。

List#get方法,以int为参数,表示该列表中要返回的元素的索引(exampleList.get(0)将返回第一个元素)

通过使用 A) 解决方案(使用 setter):

exampleList.get(0).setPopulation(new BigDecimal(100));

通过使用 B) 解决方案:

exampleList.get(0).population = new BigDecimal(100);

现在在流的情况下,您必须添加要应用的过滤器才能返回所需的对象。

exampleList.stream().filter(c -> c.getPopulation().intValue() == 80).findFirst().get()

当然,你可以使用一个简单的循环来检查值

//with getters and setters
for (constructor c : exampleList)
{
    if (c.getPopulation().intValue() == 80)
        c.setPopulation(new BigDecimal(100));
}

// without 
for (constructor c : exampleList)
{
    if (c.population.intValue() == 80)
        c.population = new BigDecimal(100);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多