【问题标题】:Arraylist containing Integers and Strings包含整数和字符串的数组列表
【发布时间】:2013-08-04 16:36:12
【问题描述】:

我想创建一个包含整数和字符串的 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 中。

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

【问题讨论】:

  • 是的,您可以创建一个ArrayList&lt;Object&gt;,但话虽如此,我对您的建议是:不要。不要创建具有混合类型的列表,因为这表明您的程序设计已损坏并且需要改进以便不需要这种怪物。
  • 为什么要在一个 ArrayList 中混合两种不同的类型?
  • 任何答案也应该解释为什么这是一个坏主意。我对所有不投票的人都投-1票。
  • 也许如果您解释一下您想要它的用途,我们可以建议一些更好的方法。
  • @HovercraftFullOfEels 与其对每个人都投反对票,不如添加一个解释它的答案?

标签: java generics arraylist


【解决方案1】:

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

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));

【讨论】:

    【解决方案2】:

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

    如果没有,那么您应该选择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 
        }
    }
    

    【讨论】:

      【解决方案3】:
      List<Object> oList=new ArrayList<Object>();
      

      【讨论】:

      • 我不明白你为什么这么生气?他只是在问一个问题,我给出了正确的答案。这个解决方案的危险方面是另一个问题。
      • 我没有生气。但我不喜欢作为答案给出的糟糕建议。
      【解决方案4】:

      您可以使用标记的总和类型Either&lt;A, B&gt;Left&lt;A, B&gt;Right&lt;A, B&gt;。在 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&lt;Either&lt;Integer, String&gt;&gt;

      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 更安全。

      【讨论】:

        【解决方案5】:

        我正在为您提供在我的项目inquiryhere.com Click here to Visit 中实施的示例

        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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-20
          • 2017-11-04
          • 2013-01-24
          • 1970-01-01
          • 1970-01-01
          • 2022-01-08
          • 2018-12-18
          • 1970-01-01
          相关资源
          最近更新 更多