1

I have an arraylist which is conformed of objects which have a name and a value so the arraylist is:

name  value
A     1
B     10
C     23
D     45

How would you loop the ArrayList searching for 2 names like C and D, and get their respective values: 23, and 45?

4
  • What kind of objects are in the list? Your "structure" is unclear to those of us to can't see your code. Commented Mar 30, 2011 at 0:12
  • Sorry, what? Arraylist is not key->value like a HashMap or similar is. Your question makes no sense. Commented Mar 30, 2011 at 0:13
  • 1
    Are your name-value pairs stored in an object that you've defined? ArrayLists typically take a single data type e.g. ArrayList<Integer> or ArrayList<String>, unless you've defined some kind of object that has both as instance variables. You might want to investigate the HashMap<ElemType, ElemType> collection class instead. Commented Mar 30, 2011 at 0:14
  • Yes my arraylist is of type node wich has several elements, but I am only interested in name and value.. Commented Mar 30, 2011 at 0:29

2 Answers 2

7

I'm assuming you mean that you have objects in the array list which have a name and value?

You could do something like this:

for(MyObj obj : list) {
    if(obj.getName().equals("C") || obj.getName().equals("A")){
          System.out.println("Value: " + obj.getValue);
    }
}

But your best bet may be to create a Hashmap of String to value:

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

Then you can simply call

valueMap.get("A");

which will return the value associated with A.

Sign up to request clarification or add additional context in comments.

6 Comments

How is that supposed to work? Object has no method 'getName()'. You'd have to create a subclass and implement that method.
Ah yeah, sorry I wrote object when it should have been anything else.
Map<String, int> valueMap = new HashMap<String, int>(); get me an error int, how to declare it
oh sorry it should be Integer rather than int.
and how do I insert elements in hash
|
0
for (MyObj obj : list) {
    // Here check if obj.getAAA() equals to "C" etc
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.