如何在 ArrayList 对象中存储方法或值

下面是我的主要课程


ArrayList<String> e = new ArrayList<>();

e.add("Mark");

下面是我的方法类


int counter = 0;

public int increaseCounter(){

    counter++;

    return counter;

}

我如何做类似的事情


    e.get(0) = method.increaseCounter();

所以马克的计数器可以是 1


喵喔喔
浏览 266回答 3
3回答

临摹微笑

有一张地图,如:-Map<String, Integer> e = new HashMap<>();e.put("Mark", 0);然后为 增加计数器Mark,调用e.merge("Mark", 1, Integer::sum);完整示例:-public static void main(String[] args) {&nbsp; &nbsp; Map<String, Integer> e = new HashMap<>();&nbsp; &nbsp; e.put("Mark", 0);&nbsp; &nbsp; increaseCounter(e, "Mark");&nbsp; &nbsp; System.out.println(e.get("Mark"));}private static void increaseCounter(Map<String, Integer> e, String key) {&nbsp; &nbsp; e.merge(key, 1, Integer::sum);}印刷 1

开心每一天1111

你可以使用这个:import java.util.Map;import java.util.HashMap;Map<String, Integer> e = new HashMap<String, Integer>();e.put("Mark", 0);

慕桂英3389331

你必须在面向对象的编程中工作才能做到这一点。例如class Data{&nbsp; &nbsp;private int counter = 0;&nbsp; &nbsp;public int increaseCounter(){&nbsp; &nbsp;counter++;&nbsp; &nbsp;return counter;&nbsp;}}然后只使用 //Java 5-9 ...&nbsp; List<Data> e = new ArrayList<>();&nbsp; e.add(new Data());或 //Java 10+...&nbsp;var e = new ArrayList<Data>();&nbsp;e.add(new Data());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java