3

I have been running into this problem sometimes when programming.

Imagine I have a table of data with two columns. The first column has strings, the second column has integers.

I want to be able to store each row of the table into a dynamic array. So each element of the array needs to hold a string and an integer.

Previously, I have been accomplishing this by just splitting each column of the table into two separate ArrayLists and then when I want to add a row, I would call the add() method once on each ArrayList. To remove, I would call the remove(index) method once on each ArrayList at the same index.

But isn't there a better way? I know there are classes like HashMap but they don't allow duplicate keys. I am looking for something that allows duplicate entries.

I know that it's possible to do something like this:

ArrayList<Object[]> myArray = new ArrayList<Object[]>();
myArray.add(new Object[]{"string", 123});

I don't really want to have to cast into String and Integer every time I get an element out of the array but maybe this is the only way without creating my own? This looks more confusing to me and I'd prefer using two ArrayLists.

So is there any Java object like ArrayList where it would work like this:

ArrayList<String, Integer> myArray = new ArrayList<String, Integer>();
myArray.add("string", 123);
1

9 Answers 9

9

Just create simple POJO class to hold row data. Don't forget about equals and hashCode and prefer immutable solution (without setters):

public class Pair {
    private String key;
    private Integer value;

    public Pair(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public Integer getValue() {
        return value;
    }

    // autogenerated

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Pair)) return false;

        Pair pair = (Pair) o;

        if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
        if (value != null ? !value.equals(pair.value) : pair.value != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = key != null ? key.hashCode() : 0;
        result = 31 * result + (value != null ? value.hashCode() : 0);
        return result;
    }
}

Usage:

    List<Pair> list = new ArrayList<Pair>();
    list.add(new Pair("string", 123));

Note: in other languages there are build-in solutions for it like case-classes and tuples in Scala.

4

Create a Row class that holds the data.

package com.stackoverflow;

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

/**
 * @author maba, 2012-10-10
 */
public class Row {
    private int intValue;
    private String stringValue;

    public Row(String stringValue, int intValue) {
        this.intValue = intValue;
        this.stringValue = stringValue;
    }

    public int getIntValue() {
        return intValue;
    }

    public String getStringValue() {
        return stringValue;
    }

    public static void main(String[] args) {
        List<Row> rows = new ArrayList<Row>();
        rows.add(new Row("string", 123));
    }
}
3

You can create very simple object, like :

public class Row{
   private String strVal;
   private Integer intVal;

   public Row(String s, Integer i){
        strVal = s;
        intVal = i;
   }

   //getters and setters
}

Then use it as follows :

ArrayList<Row> myArray = new ArrayList<Row>();
myArray.add(new Row("string", 123));
3

Map is the option if you are sure that any one value among integer or string is unique. Then you can put that unique value as a key. If it is not true for your case, creating a simple POJO is best option for you. Infact, if in future, there a chance to come more values (columns) per row then also using a POJO will be less time consuming. You can define POJO like;

public class Data {

 private int intValue;
 private String strValue;

 public int getIntValue() {
   return intValue;
 }

 public void setIntValue(int newInt) {
  this.intValue = newInt;
 }

 public String getStrValue() {
   return strValue;
 }

 public void setStrValue(String newStr) {
  this.strValue = newStr;
 }

And in the class you can use it like;

ArrayList<Data> dataList = new ArrayList<Data>();  
Data data = new Data();  
data.setIntValue(123);  
data.setStrValue("string");  
dataList.add(data);
2

You should create a class (e.g. Foo) that contains an int and a String.

Then you can create an ArrayList of Foo objects.

List<Foo> fooList = new ArrayList<Foo>();

1

This is called a map my friend. It is similar to a dictionary in .net

http://docs.oracle.com/javase/6/docs/api/java/util/Map.html

3
  • 2
    The question does not suggest the use of a Map. The OP is maintaining two parallel ArrayLists.
    – jahroy
    Oct 10, 2012 at 5:02
  • 1
    ok well you better go downvote all the other answers and comment on them
    – MikeB
    Oct 10, 2012 at 5:04
  • 1
    I think creating a POJO is a better idea. But this sure doesn't deserve a downvote, as it solves the problem, plus the question somewhat looks likes it's looking for a Map. :) Oct 10, 2012 at 5:09
0

HashMap my be the class you are looking for assuming "string" going to different for different values. Here is documentation on HashMap

Example:

HashMap<String, Integer> tempMap = new HashMap<String, Integer>();
tempMap.put("string", 124);

If you need to add more than one value, you may create HashMap<String, ArrayList> like that.

0

you can use google collection library Guava there is a Map called Multimap. It is collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

1
  • Or better yet, a Guava Multimap.
    – yshavit
    Oct 10, 2012 at 5:03
0

Use Map to solve this problem:

Map<String, Integer> map = new HashMap<String, Integer>();

Eg:

map.put("string", 123);
1
  • 2
    You don't mean new Map... Do you? Oct 10, 2012 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.