user2648572
user2648572

Reputation: 163

Arraylist containing Integers and Strings

I want to create a Arraylist which should contain Integers and Strings.. Is that possible?

I have created two Arraylist as given below:

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

I want to put intList & strList into a new ArrayList.

Can I do that?? If so, How??

Upvotes: 16

Views: 101176

Answers (6)

Osamah
Osamah

Reputation: 1

If you're trying to print both at same time try 2D array

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

Upvotes: 0

Aman Kumar
Aman Kumar

Reputation: 41

I am providing you that example which is implement in my project inquiryhere.com Click here to Visit

java code...

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 code, I am working with jstl

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

Upvotes: 2

MAnyKey
MAnyKey

Reputation: 567

You can use tagged sum types: Either<A, B> is either Left<A, B> or Right<A, B>. In Java it will look like:

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

So, you can use 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;
  }
}

This approach is more type-safe than using Object.

Upvotes: 2

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

You can do this as follows but have to give up on generics for the list container.

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

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

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

But, a better way would be to use a Map to keep track of the two lists since the compiler would no longer be able to prevent you from mixing types like putting a String into an Integer list.

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

Upvotes: 11

Suresh Atta
Suresh Atta

Reputation: 121998

If it's avoidable, please avoid this list of Object type. Go for individual lists.

If not then you should go for type of Object

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

which accept all the type Objects, but have to take care while retrieving.

Checking the objects while retrieving

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

Upvotes: 8

ihsan kocak
ihsan kocak

Reputation: 1581

List<Object> oList=new ArrayList<Object>();

Upvotes: 3

Related Questions