包含整数和字符串的数组列表

问题描述 投票:0回答:6

我想创建一个包含整数和字符串的数组列表..这可能吗?

我创建了两个Arraylist,如下所示:

ArrayList<Integer> intList=new ArrayList<Integer>();
    intList.add(1);
    intList.add(2);

ArrayList<String> strList=new ArrayList<String>();
    strList.add("India");
    strList.add("USA");
    strList.add("Canada");

我想将 intList 和 strList 放入一个新的 ArrayList 中。

我可以这样做吗?如果是这样,怎么办??

java generics arraylist
6个回答
11
投票

您可以按如下方式执行此操作,但必须放弃列表容器的泛型。

List<List> listOfMixedTypes = new ArrayList<List>();

ArrayList<String> listOfStrings = new ArrayList<String>();
ArrayList<Integer> listOfIntegers = new ArrayList<Integer>();

listOfMixedTypes.add(listOfStrings);
listOfMixedTypes.add(listOfIntegers);

但是,更好的方法是使用

Map
来跟踪两个列表,因为编译器将不再能够阻止您混合类型,例如将字符串放入整数列表中。

Map<String, List> mapOfLists = new HashMap<String, List>();

mapOfLists.put("strings", listOfStrings);
mapOfLists.put("integers", listOfIntegers);

mapOfLists.get("strings").add("value");
mapOfLists.get("integers").add(new Integer(10));

8
投票

如果可以避免,请避免使用此对象类型列表。寻找个人清单。

如果没有,那么你应该选择

Object

类型
List<Object> list = new ArrayList<Object>();

它接受所有类型的对象,但在检索时必须小心。

检索时检查对象

for (Object obj: list) {
    if (obj instanceof String){
        // this  is string 
    } else if (obj instanceof Integer) {
       // this  is Integer 
    }
}

2
投票
List<Object> oList=new ArrayList<Object>();

2
投票

您可以使用标记总和类型

Either<A, B>
Left<A, B>
Right<A, B>
。在 Java 中,它看起来像:

public interface Either<A, B>;
public class Left<A, B> implements Either<A, B> {
  public final A value;
  public Left(A value) {
    this.value = value;
  }
}
public class Right<A, B> implements Either<A, B> {
  public final B value;
  public Right(B value) {
    this.value = value;
  }
}

所以,您可以使用

ArrayList<Either<Integer, String>>

for (Either<Integer, String> either : intsOrStrings) {
  if (either instanceof Left) {
    Integer i = ((Left<Integer, String>) either).value;
  } else if (either instanceof Right) {
    String s = ((Right<Integer, String>) either).value;
  }
}

这种方法比使用

Object
更加类型安全。


2
投票

我向您提供在我的项目quiryhere.com中实施的示例单击此处访问

java代码...

public class hash_Map {
public HashMap<Integer, String> getQuestionTagWithId(int qId) throws SQLException{
    DatabaseConnection dc = new DatabaseConnection();
    HashMap<Integer, String> map = new HashMap<>();
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try{
        con = dc.getConnection();
        String sql = "select tag_id as unique_id,(select topic_name from topic where unique_id = question_topic_tag.tag_id)topic_name from question_topic_tag where question_id =?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, qId);
        rs = ps.executeQuery();
        while(rs.next()){
            int questionTagId = rs.getInt("unique_id");
            String questionTag = rs.getString("topic_name");
            map.put(questionTagId, questionTag);
        }
    }catch(SQLException msg){
        throw msg;
    }finally{
          if(rs != null){
            try{
                rs.close();
            }catch(SQLException msg){

            }
        }
        if(ps != null){
            try{
                ps.close();
            }catch(SQLException msg){

            }
        }
        if(con != null){
            try{
                con.close();
            }catch(SQLException msg){

            }
        }
    }
    return map;
}}

Jspbean

<jsp:useBean class="com.answer.hash_Map" id="SEO"  scope="page" />

jstl代码,我正在使用jstl

 <c:forEach items="${SEO.getQuestionTagWithId(param.Id)}" var="tag" varStatus="loop">
                       ${tag.key}${tag.value}
 </c:forEach>

0
投票

如果您想同时打印两者,请尝试 2D 数组

String[][] fruits = {{"Orange", "Lemon", "Grapes"},
                     {"Mango", "Melon", "Apples"}};
    int[][] prices = {{4, 6, 7},
                     {14, 3, 6}};
    int c = 0;
    for (String[] x : fruits) {
        c++;
        System.out.println(fruits[c - 1][c - 1] + " price is " + prices[c - 1][c - 1]);
    }
© www.soinside.com 2019 - 2024. All rights reserved.