【问题标题】:Java associate string with int arrayJava 将字符串与 int 数组关联
【发布时间】:2017-01-13 02:25:05
【问题描述】:

我正在开发一个从网站获取学校分数和学科名称的程序。我想将一个字符串与一个 int 数组相关联,以便每个主题都引用它的标记。有可能吗?

编辑:我的意思是这样的

array = 
{"english": [5, 7, 9],
 "history": [4, 8, 6],
 .....
}

【问题讨论】:

  • 你是什么意思'关联'?
  • 我的意思是一个关联数组,一个字典
  • 你的意思是this 那种'字典'?你需要一张地图。
  • 是的,类似的

标签: java arrays dictionary


【解决方案1】:

您可以将其存储在 Map(集合框架)中。下面是示例代码

    Map<String, Integer[]> aMap = new HashMap<String, Integer[]>();
    aMap.put("Maths", new Integer[]{1,2,3,4});
    Integer[] marks = aMap.get("Maths");
    for(int mark: marks){
        System.out.println(mark);
    }

如果您正在寻找更广泛的方法,您可以参考ListTable

【讨论】:

  • 为什么在int[] 更好时使用Integer[],因为您不希望数组中有空值?
【解决方案2】:

尝试将字符串映射到整数列表。像这样的:

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//create the map like this
Map<String, List<Integer>> studentMarks = new HashMap<String, List<Integer>>();

//put values in the map like this   
studentMarks.put("Student name 1", Arrays.asList(65, 70, 85, 45));
studentMarks.put("Student name 2", Arrays.asList(95, 56, 34, 41));


//retrieve the marks for one student like this  
List<Integer> marksForStudent1 = studentMarks.get("Student name 1");

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多