Java中,怎样把字符串和整数存到同一个数组中?

字符串和整数都要保留其原来的数据类型
使用其他编程语言也可以


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

public class Test {

public static void main(String[] args) {
int length = 5;
HashMap[] map = new HashMap[length];
//向数组添加两个数,一个是String,一个是int
boolean setValue = setValue(map, 0, 1);
if (setValue) {
System.out.println("添加成功!");
}
boolean setValue1 = setValue(map, 1, "a");
if (setValue1) {
System.out.println("添加成功!");
}
//取出数组中第index位的值
int index = 1;
Iterator it = map[index].keySet().iterator();
Object key;
while (it.hasNext()) {
key = it.next();
if (key.equals("String")) {
//StrValue为得到的String值
String StrValue = (String) map[index].get(key);
System.out.println(key + ":" + StrValue);
} else {
//intValue为得到的int值
int intValue = (int) map[index].get(key);
System.out.println(key + ":" + intValue);
}
}
}

/**
 *@param  index 向第几位添加 
 *@param  value 添加的内容
 * */
public static boolean setValue(HashMap[] map, int index, String value) {
if (index > map.length)
return false;
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("String", value);
map[index] = hashMap;
return true;
}

/**
 *@param  index 向第几位添加 
 *@param  value 添加的内容
 * */
public static boolean setValue(HashMap[] map, int index, int value) {
if (index > map.length)
return false;
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("Integer", value);
map[index] = hashMap;
return true;
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-03-22

使用object类型就可以

import java.util.ArrayList;
import java.util.List;

public class Test {
public static void main(String[] args) {
int a = 520;
String b = "xing";
List<Object> list = new ArrayList<>();
list.add(a);
list.add(b);
list.forEach(System.out::println);
}
}

本回答被提问者和网友采纳
第2个回答  2019-03-22
java的list是可以做的,只要定义的时候不加范型就行。
相似回答